简体   繁体   English

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

[英]Python - Only print lines if contains the elements of a tuple from a List

I've the following text file:我有以下文本文件:

We are playing football at World Cup
teste
We are playing football
Playing test 
World Cup Football

And I only want to extract the lines that contains (World Cup and Football) or ('Playing', 'test ').我只想提取包含 (World Cup and Football) 或 ('Playing', 'test') 的行。

For example, based on my text file I only want to extract this:例如,基于我的文本文件,我只想提取这个:

We are playing football at World Cup
Playing test 
World Cup Footbal

Basically I only want to extract if the line contains the two values from each tuple.基本上我只想提取该行是否包含每个元组中的两个值。

For that I am trying the following code:为此,我正在尝试以下代码:

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)

But with my code I am having the following error:但是我的代码出现以下错误:

TypeError: 'in <string>' requires string as left operand, not tuple

How can I do this?我怎样才能做到这一点?

Thanks谢谢

You can try with combination of any and all :您可以尝试组合anyall

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

You can check any from the list of words and all from items of the list.您可以从单词列表中检查任何一个,也可以从列表的项目中检查所有内容。

( Testing without file ) 无文件测试

# 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)

Output:输出:

We are playing football at World Cup
Playing test
World Cup Football

As mentioned in the comment below, if second element is not tuple, it causes unexpected result.正如下面的评论中提到的,如果第二个元素不是元组,则会导致意外结果。 Using test example, following shows error as it is comparing if all characters are same instead of words:使用测试示例,以下显示错误,因为它比较所有字符而不是单词是否相同:

x = "test palying"
if all(w.lower() in x for w in words[1]):
    print("ERROR")

You were really close, you just needed one more loop:你真的很接近,你只需要一个循环:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM