簡體   English   中英

Python-在文本文件中搜索列表中的任何字符串

[英]Python - Search Text File For Any String In a List

抱歉,這是違反規則的。 我嘗試創建一個簡單的Python腳本,該腳本在文本文件中搜索列表中的任何字符串。

KeyWord =['word', 'word1', 'word3']

if x in Keyword in open('Textfile.txt').read():
    print('True')

當我運行代碼時,盡管我不確定為什么會出現“名稱錯誤:未定義名稱'x'”的問題?

x未定義。 您忘記了定義它的循環。 這將創建一個生成器,因此您將需要使用any生成器:

KeyWord =['word', 'word1', 'word3']

if any(x in open('Textfile.txt').read() for x in KeyWord):
    print('True')

此方法有效,但是它將多次打開並讀取文件,因此您可能需要

KeyWord = ['word', 'word1', 'word3']

file_content = open('test.txt').read()

if any(x in file_content for x in KeyWord):
    print('True')

這也適用,但你應該更喜歡使用with

KeyWord = ['word', 'word1', 'word3']

with open('test.txt') as f:
    file_content = f.read()

if any(x in file_content for x in KeyWord):
    print('True')

一旦在文件中找到列表中的第一個單詞,以上所有解決方案都將停止。 如果這是不希望的,那么

KeyWord = ['word', 'word1', 'word3']

with open('test.txt') as f:
    file_content = f.read()

for x in KeyWord:
    if x in file_content:
        print('True')

您可以使用for循環執行此操作,如下所示。 您的代碼的問題是它不知道x是什么。 您可以在循環內部定義它,以使x等於每次循環運行在KeyWord列表中的值。

KeyWord =['word', 'word1', 'word3']
with open('Textfile.txt', 'r') as f:
    read_data = f.read()
for x in KeyWord:
    if x in read_data:
        print('True')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM