[英]Python: detect if just one of the given words appear in text file
I am trying to get my program to see if one of the 3 words in "words" appears in the fine kal.txt, just the fact that one of the words appear us enough, but I can't seem to get it working.我试图让我的程序查看“words”中的 3 个词之一是否出现在精细的 kal.txt 中,只是其中一个词出现在我们身上就足够了,但我似乎无法让它工作。
My Code:我的代码:
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
This is the output I get in cmd:这是我在cmd中得到的输出:
3
That is of course because it's printing the len_words which is 3.那当然是因为它打印的是 3 的 len_words。
Any suggestions why, or does anyone have a solution?任何建议为什么,或者有没有人有解决方案?
First we read the file content.首先我们读取文件内容。 Then we loop over each word and check if it is in the text.
然后我们遍历每个单词并检查它是否在文本中。 If it is we write our info and leave the loop.
如果是,我们写我们的信息并离开循环。
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
Please note the use of the with
context manager.请注意
with
上下文管理器的使用。 When you use with
with open
there's no need to close the file after the work is done - a task that you forgot to do in your program.当您使用
with
with open
,工作完成后无需关闭文件 - 您忘记在程序中执行的任务。
Additional note: A list is iterable.附加说明:列表是可迭代的。 There's no need to use a counter and access the elements with their index.
无需使用计数器并通过索引访问元素。 Working with an index is slower, harder to read and so it is considered "unpythonic".
使用索引更慢,更难阅读,因此它被认为是“unpythonic”。 Just loop over the values themselves.
只需循环值本身。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.