首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果包含列表中元组的元素,则仅打印行。

如果包含列表中元组的元素,则仅打印行。
EN

Stack Overflow用户
提问于 2019-04-08 15:07:23
回答 2查看 474关注 0票数 2

我有以下文本文件:

代码语言:javascript
复制
We are playing football at World Cup
teste
We are playing football
Playing test 
World Cup Football

我只想提取包含(世界杯和足球)或(“打”,“测试”)的线条。

例如,基于我的文本文件,我只想提取以下内容:

代码语言:javascript
复制
We are playing football at World Cup
Playing test 
World Cup Footbal

基本上,我只想从每个元组中提取包含这两个值的行。

为此,我正在尝试以下代码:

代码语言:javascript
复制
file = 'text.txt'
words = [('Football','World Cup'), ('Playing test ')]
with open(file, "r") as ins:
    for line in ins:
        if all(x in line.lower() for x in words):
            print(line)

但是,对于我的代码,我有以下错误:

代码语言:javascript
复制
TypeError: 'in <string>' requires string as left operand, not tuple

我该怎么做?

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-04-08 15:21:15

您可以尝试使用anyall组合。

代码语言:javascript
复制
if any(all(words.lower() in line.lower() for words in word_tuples) for word_tuples in words)

您可以从单词列表和列表中的所有项中检查任何内容。

(没有文件的测试)

代码语言:javascript
复制
# Note: second element needs to be tuple else causes unexpected results
words = [('Football','World Cup'), ('Playing test',)] 
ins = ["We are playing football at World Cup",
       "teste",
       "We are playing football",
       "Playing test",
       "World Cup Football"]

for line in ins:
    if any(all(words.lower() in line.lower() for words in word_tuples) for word_tuples in words):
        print(line)

输出:

代码语言:javascript
复制
We are playing football at World Cup
Playing test
World Cup Football

如下面的注释中所述,如果第二个元素不是元组,则会导致意外的结果。使用测试示例,如果所有字符都是相同的,而不是单词,则在比较时将显示错误:

代码语言:javascript
复制
x = "test palying"
if all(w.lower() in x for w in words[1]):
    print("ERROR")
票数 1
EN

Stack Overflow用户

发布于 2019-04-08 15:15:09

你真的很亲密,你只需要再循环一次:

代码语言:javascript
复制
file = 'text.txt'
words = [('Football','World Cup'), ('Playing test ')]
with open(file, "r") as ins:
    for line in ins:
        for tup in words:
            if all(word.lower() in line.lower() for word in tup):
                print(line)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55576489

复制
相关文章

相似问题

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