您好,我有这段代码,它可以过滤所有行中的一个特定单词('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)发布于 2014-03-31 23:00:56
使用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']):
...发布于 2014-03-31 23:03:09
您可以使用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']https://stackoverflow.com/questions/22764958
复制相似问题