我有以下文本文件:
We are playing football at World Cup
teste
We are playing football
Playing test
World Cup Football我只想提取包含(世界杯和足球)或(“打”,“测试”)的线条。
例如,基于我的文本文件,我只想提取以下内容:
We are playing football at World Cup
Playing test
World Cup Footbal基本上,我只想从每个元组中提取包含这两个值的行。
为此,我正在尝试以下代码:
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)但是,对于我的代码,我有以下错误:
TypeError: 'in <string>' requires string as left operand, not tuple我该怎么做?
谢谢
发布于 2019-04-08 15:21:15
您可以尝试使用any和all组合。
if any(all(words.lower() in line.lower() for words in word_tuples) for word_tuples in words)您可以从单词列表和列表中的所有项中检查任何内容。
(没有文件的测试)
# 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)输出:
We are playing football at World Cup
Playing test
World Cup Football如下面的注释中所述,如果第二个元素不是元组,则会导致意外的结果。使用测试示例,如果所有字符都是相同的,而不是单词,则在比较时将显示错误:
x = "test palying"
if all(w.lower() in x for w in words[1]):
print("ERROR")发布于 2019-04-08 15:15:09
你真的很亲密,你只需要再循环一次:
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)https://stackoverflow.com/questions/55576489
复制相似问题