【问题标题】:Python - Search Text File For Any String In a ListPython - 在文本文件中搜索列表中的任何字符串
【发布时间】:2018-02-28 15:33:39
【问题描述】:

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

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

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

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

【问题讨论】:

  • 如果三个关键字都出现在文档中,“True”应该打印多少次?

标签: python-3.x


【解决方案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')

【讨论】:

  • 谢谢大家的支持,我又看了一遍代码,发现我没有在 KeyWord 中为 x 定义 x ' KeyWord =['word', 'word1', 'word3'] : if x in open('Textfile.txt').read(): print('True') '
  • 这是您正在寻找@LockTheTaskBar 的解决方案,还是如果文件中有任何单词,您只希望它打印一次 True?目前,它会为列表中的每个单词打印 True,并且该单词也在文件中。
  • 感谢@Zack Tarr,这就是我想要实现的目标。我将尝试实现一种将结果存储在单独的文本文件中的方法。还要考虑存储出现的列表中的单词,而不是真假。
  • 那么这对你来说应该可以正常工作。您可以在if x in read_data 段中使用x 将单词附加到“找到的单词”的新列表中祝你好运!
  • 感谢@Zack Tarr,将尝试此方法,感谢支持。
【解决方案2】:

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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    相关资源
    最近更新 更多