首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于词表的行过滤

基于词表的行过滤
EN

Stack Overflow用户
提问于 2014-03-31 22:56:58
回答 2查看 233关注 0票数 1

您好,我有这段代码,它可以过滤所有行中的一个特定单词('test',我想知道是否有人可以帮助解释如何过滤包含多个单词的行,所以如果我有一个列出所有过滤单词的文件和一个源文件,我将能够显示其中包含任何过滤单词的所有源行。谢谢!

代码语言:javascript
复制
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)
EN

回答 2

Stack Overflow用户

发布于 2014-03-31 23:00:56

使用any

代码语言:javascript
复制
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']):
    ...
票数 4
EN

Stack Overflow用户

发布于 2014-03-31 23:03:09

您可以使用any()in运算符:

代码语言:javascript
复制
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)]

输出:

代码语言:javascript
复制
rumpelstiltskin foo bar
gretchel bar
hansel foo
['rumpelstiltskin foo bar', 'gretchel bar', 'hansel foo']
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22764958

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档