【问题标题】:Searching for substrings in file.readlines() in python在 python 中的 file.readlines() 中搜索子字符串
【发布时间】:2014-11-14 12:48:16
【问题描述】:

刚从 python 开始,如果我听起来很笨,请原谅。

假设以下输入:
我的文件内容:

我们喜欢独角兽
我们喜欢啤酒
我们喜欢免费(一种免费的啤酒)

我预计以下内容会返回 true:

# my_file = some path to valid file
with open(my_file) as f:
    lines = f.readlines()
    if 'beer' in lines:
        print("found beer") # this does not happen

还是我太习惯了c#的方式,之后我会得到所有匹配的行:

// assuming I've done a similar lines = open and read from file
var v = from line in lines
        where line.Contains("beer")
        select line;

例如,获取那些包含beer 的行的pythonian 等价物是什么?

【问题讨论】:

    标签: c# python string search


    【解决方案1】:

    你很接近,你需要检查每一行中的子字符串,而不是行列表。

    with open(my_file) as f:
        for line in f:
            if 'beer' in line:
                print("found beer")
    

    举个例子,

    lines = ['this is a line', 'this is a second line', 'this one has beer']
    

    第一种情况基本上就是你想要做的

    >>> 'beer' in lines
    False
    

    这就是我上面展示的代码的作用

    >>> for line in lines:
            print('beer' in line)
    
    False
    False
    True
    

    【讨论】:

    • 是的,我发现我需要第二个循环...因为readlines() 基本上返回带有\n 的行...感觉很奇怪,我不能使用那...想知道with open(my_file).readlines() as lines:是否可以工作...但它不会...
    【解决方案2】:

    这就是你的做法:

    with open(my_file) as f:
        data = f.read()  # reads everything to a string
        if 'beer' in data:
            print("found beer")
    

    或者更有效:

    with open(my_file) as f:
        for line in f:
            if 'beer' in line:
                print("found beer")
    

    【讨论】:

    • 第一个选项不是我想要的。我实际上正在寻找特定的行。我喜欢第二个...不知道我可以完全跳过readlines() ...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-11
    • 2011-11-30
    • 2016-04-20
    • 2019-10-06
    • 2016-04-21
    相关资源
    最近更新 更多