我正在尝试让我的程序查看“words”中的 3 个单词之一是否出现在罚款 kal.txt 中,事实是其中一个单词出现得足够多,但我似乎无法理解它工作了。
我的代码:
textring = open('kal.txt', 'r')
words =['flapping', 'Unexpected', 'down']
len_words = len(words)
print(len_words)
counter = 0
while counter < len_words:
if words[counter] in textring:
print('success')
SAVE_FILE = open('warnings/SW_WARNING.txt', 'w+')
SAVE_FILE.write(textring)
counter += 1
这是我在 cmd 中得到的输出:
3
那当然是因为它打印的是 len_words,即 3。
有什么建议吗,或者有人有解决方案吗?
最佳答案
首先我们读取文件内容。然后我们循环遍历每个单词并检查它是否在文本中。如果是,我们写入信息并离开循环。
with open('kal.txt', 'r') as infile:
text = infile.read()
words = ['flapping', 'Unexpected', 'down']
for word in words:
if word in text:
print('success')
with open('warnings/SW_WARNING.txt', 'w+') as save_file:
save_file.write(text)
break
请注意with
上下文管理器的使用。当您将 with
与 open
一起使用时,无需在工作完成后关闭文件 - 这是您在程序中忘记执行的任务。
附加说明:列表是可迭代的。无需使用计数器并通过索引访问元素。使用索引速度较慢,难以阅读,因此它被认为是“unpythonic”。只需循环值本身即可。
关于Python:检测文本文件中是否只出现给定的单词之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59138412/