2013-03-22 39 views
0

我有一個從我打開的txt文檔中的行的列表。搜索一個文件並計數

list = ['hello there','how are you','im good thanks'] 

進出口尋找通過這個列表來搜索,看看這個詞「你好」出現在它再算上它出現在那裏的次數。除此之外,我已經將文本文件打開成一個列表,然後用空格分隔它。

list = ['hello','there','how','are','you','im','good','thanks'] 

會變成這樣如果是的話我會怎麼做這更好的方法來試圖通過列表「你好」的外觀和指望它在使用前,?

+2

這個名字「奧賽羅」包含單詞「你好」還是不? – DSM 2013-03-22 12:46:33

回答

3

編輯:添加line.split()以防Othello在文檔中。此外line.lower()處理大寫的「你好」

>>> lines = ['hello there','how are you','im good thanks'] 
>>> sum(line.lower().split().count('hello') for line in lines) 
1 

你可能只是這樣做直接從像文件:

with open('file.txt') as f: 
    sum(line.lower().split().count('hello') for line in f) 
0

你的第二個方法,你可以隨便去

list.count("hello") 
相關問題