Python:检测文本文件中是否只出现给定单词之一
Python: detect if just one of the given words appear in text file
我正在尝试让我的程序查看 "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"。只需遍历值本身。
我正在尝试让我的程序查看 "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"。只需遍历值本身。