2014-03-31 67 views
1

嗨我有這樣的代碼,用於過濾一個特定單詞的所有行('測試',我想知道是否有人可以通過解釋如何用多於一個單詞來過濾行,所以如果我不得不使用any文件列出了所有過濾詞和源文件我將能夠顯示所有有過任何過濾器的話在它由於源線基於Word列表的過濾行

def cat(openfile): 
    with open(openfile) as file: 
    return file.read() 

def getlinewith(filecontents, containing): 
    for item in filecontents.split('\n'): 
    if containing in item: 
     yield item.strip() 

matchedlines = [] 

for line in getlinewith(cat('C\\testdata_all.txt'), 'test'): 
    print(line) 
    matchedlines.append(line) 

print(matchedlines) 
+0

那麼,什麼是你的問題? – sshashank124

+0

對不起,上面的方法只需要一個單詞而不是100個例子 –

+0

題外話:在你的例子中,你正在尋找一個包含單詞'test'的行或者任何有'test'的行嗎?因爲你所擁有的東西也會與諸如「比賽」,「抗議」,「測試」等詞語匹配...... – skamsie

回答

3

:!

def getlinewith(filecontents, containings): 
    for item in filecontents.split('\n'): 
    if any(containing in item for containing in containings): 
     # `any` will return `True` as soon as it find a match 
     yield item.strip() 

matchedlines = [] 

for line in getlinewith(cat(r'C:\testdata_all.txt'), ['test', 'other_word']): 
    ... 
2

您可以使用any()in操作或:

lines = """ 
rumpelstiltskin foo bar 
hansel rumpelstiltskin 
gretchel bar 
hansel foo 
""".splitlines() 

seek = ['foo', 'bar'] 

for line in lines: 
    if any(word in line for word in seek): 
     print line 

print [line for line in lines if any(word in line for word in seek)] 

輸出:

rumpelstiltskin foo bar 
gretchel bar 
hansel foo 
['rumpelstiltskin foo bar', 'gretchel bar', 'hansel foo']