[英]Why does my Python code work in Jupyter Notebook but not as a script?
[英]Python - why does my short code not work?
為什么下面的代碼不起作用? 我有一個單詞列表,想在例句中檢測這些單詞。
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
它所做的只是“[在 0.3 秒內完成]”——它不應該觸發打印語句,因為示例句子中的單詞“可以”?
感謝所有提示
您的單詞包含“\\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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.