Python 从词表功能问题中搜索

Python Searching from a Wordlist Function Issues


出于某种原因,我无法理解如何获取我的单词列表以在文本文件中搜索我提供的单词列表。我确实找到了一种使用 "elif" 语句创建单词列表的方法,但我想正确地做到这一点。 - Python 3.7.x

name = 'Foo'
name1 = 'Bar'
name2 = 'python'
searchfile = open("test.txt","r")
num_lines = 0

for line in searchfile:
    num_lines += 1
    line = line.lower()
    if name in line:
        print ("Found on Line:",num_lines, line)
    elif name1 in line:
        print ("Found on Line:",num_lines, line)
    elif name2 in line:
        print ("Found on Line:",num_lines, line)

我想让 "name" 变量有一个要搜索的单词列表。像这样..但我收到错误。

name = ("foo","bar","python")
name1 = ("foo1","bar1","python1")
name2 = ("foo2","bar2","python2")

TypeError: 'in ' 需要字符串作为左操作数,而不是元组
也许如果我看到正确的代码,我的大脑就会理解它。任何帮助将不胜感激。

最简单的方法就是使用 for 循环

name = ("foo","bar","python")
for n in name:
    if n in line:
        print ("Found on Line:",num_lines, line)

这是因为在您的示例中 name 是一个元组,并且使 name in line 将尝试检查元组是否在字符串类型的行内。 您可以像这样遍历任何要检查的单词

name = ('Foo', 'Bar', 'python')
searchfile = open("test.txt","r")

for num_lines, line in enumerate(searchfile, 1):
    for word in names:
        if word.lower() in line.lower():
             print("Found on Line:", num_lines, line)

此外,如果你想像你说的那样拥有多个"names",你可以这样做:

name = ("foo","bar","python")
name1 = ("foo1","bar1","python1")
name2 = ("foo2","bar2","python2")
names = name + name1 + name2

并像以前一样迭代 for word in names。我不知道你的要求是什么,但最好创建

names = ("foo", "bar", "python", "foo1", "bar1", "python1", "foo2", "bar2", "python2")

作为单个元组而不是 N 个元组。