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

问题描述 投票:0回答:2

道歉是违反规则的。我尝试创建一个简单的Python脚本,在文本文件中搜索列表中的任何字符串。

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

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

当我运行代码时,我收到“名称错误:名称'x'未定义”,虽然我不确定为什么?

python-3.x
2个回答
1
投票

您可以使用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')

1
投票

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')
© www.soinside.com 2019 - 2024. All rights reserved.