基于Word-Lis的过滤线

2024-06-16 14:07:45 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我有一个代码,过滤一个特定单词的所有行('测试'),我想知道是否有人可以帮助解释如何过滤行不止一个单词,所以如果我有一个文件列出所有的过滤词和一个源文件,我将能够显示所有的源代码行,其中有任何过滤词。谢谢!你知道吗

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)

Tags: 代码infordeflineitem单词cat
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']

使用^{}

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']):
    ...

相关问题 更多 >