2014-11-14 70 views
0

剛開始使用python,所以如果我聽起來很厚,那麼請原諒。在python中搜索file.readlines()中的子串

假設以下輸入:
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; 

會是什麼pythonian等同於獲取那些持有beer例如線?

回答

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 
+0

是的,我已經想通了,我還需要第二次循環中......既然'readlines方法()'基本上返回線與'\ N'追加......感覺很奇怪,我不能使用它......想知道如果「打開(my_file).readlines()作爲行:'會工作...但它不會... – Noctis 2014-11-14 12:59:04

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

第一個選項是不是我想要的。我實際上是在尋找特定的線路。我喜歡第二個,但是......並不知道我可以跳過'readlines()'... – Noctis 2014-11-14 12:59:56