在python中搜索file.readlines()中的子字符串

时间:2014-11-14 12:48:17

标签: c# python string search

刚开始使用python,请原谅我听起来非常厚。

假设以下输入:
my_file内容:

  我们喜欢独角兽   我们喜欢啤酒   我们爱免费(免费啤酒)

我预计以下内容会返回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等同于什么?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

您就是这样做的:

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")