您好我有这个代码可以过滤掉一个特定单词的所有行(' test',我想知道是否有人可以通过解释如何使用多个单词过滤行来帮助,所以如果我有一个文件列出了所有的过滤词和一个源文件,我可以显示所有过滤词中的所有源行。谢谢!
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 :(得分:3)
使用any
:
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']):
...
答案 1 :(得分: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']