![](/img/trans.png)
[英]Find if lines on one file appear as words in the lines of another file in 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
那當然是因為它打印的是 3 的 len_words。
任何建議為什么,或者有沒有人有解決方案?
首先我們讀取文件內容。 然后我們遍歷每個單詞並檢查它是否在文本中。 如果是,我們寫我們的信息並離開循環。
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
with open
,工作完成后無需關閉文件 - 您忘記在程序中執行的任務。
附加說明:列表是可迭代的。 無需使用計數器並通過索引訪問元素。 使用索引更慢,更難閱讀,因此它被認為是“unpythonic”。 只需循環值本身。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.