Python-为什么我的短代码不起作用?

Python-为什么我的短代码不起作用?,python,Python,为什么下面的代码不起作用?我有一个单词列表,希望在示例句子中检测这些单词 Sentence = 'This could be a sentence' with open('Badwords_conjunctive.txt') as file: if any(word in Sentence for word in file.readlines()): print('Conjunctive should rather be avoided') Badwords_conj

为什么下面的代码不起作用?我有一个单词列表,希望在示例句子中检测这些单词

Sentence = 'This could be a sentence'

with open('Badwords_conjunctive.txt') as file:
    if any(word in Sentence for word in file.readlines()):
        print('Conjunctive should rather be avoided')
Badwords_conjunctive.txt是包含以下文本的文本文件:

could
might
may
ought
should
Would
它所做的只是“[Finished in 0.3s]”-它不应该像示例语句中的“can”这个词那样触发print语句吗

感谢所有提示

您的单词中包含“\n”字符,这就是它与您的句子不匹配的原因。比较之前,应删除“\n”:

Sentence = 'This could be a sentence'

with open('Badwords_conjunctive.txt') as file:
    if any(word.strip() in Sentence for word in file.readlines()):
        print('Conjunctive should rather be avoided')
上面的“任意”术语的格式不正确。试试这个:

Sentence = 'This could be a sentence'
with open('Badwords_conjunctive.txt') as file:
    for word in file.readlines():
        if word.strip() in Sentence.split():
             print('Conjunctive should rather be avoided')

any(word.strip()在句子中表示文件.readlines()中的word)
。readlines中的每个元素都附加了一个
\n
,因此没有匹配项。请尝试将代码分解为循环,而不是使用任何循环。打印出你正在比较的所有数值,看看你是否能看出问题所在。耶稣,谢谢你,就是这样!任何(word.strip()已解决it@Paul鲁尼-那个环看起来怎么样?蟒蛇here@Adrian_G它可能看起来像。它的等效代码(除了我的代码在找到匹配项时不停止(短路).Iy将显示代码中的两个关键问题我可以问一下,为什么您将其从“any”更改为“all”对不起,这是一个错误,它应该是any不要使用replace(最肯定不是“raplace”…;))为此,请使用strip()。count变量的用途是什么?抱歉,意外地将其留在-我刚刚删除了它