Python-如何编写不同数量的'if(condition)或if(condition)'?

时间:2019-03-31 17:51:07

标签: python list parsing if-statement

我试图在Python中创建一个解析器,该解析器将遍历多个文件,搜索给定的单词,并返回包含该字符串的所有行。

我使用的方法是从包含搜索到的单词的文档中多次复制同一行,如果该行包含用户尝试搜索的多个单词。

我当前使用的搜索方法是:

for line in range(0,length_of_documents):
    for word in range(0,words):
        if words[word] in document[line]:
            print(document[line])

要克服这个问题,我需要写一些类似的东西:

for line in range(0,length_of_documents):
    for word in range(0,words):
        if words[0] in document[line] or if words[1] in document[line] or if words[2] in document[line]:
            print(document[line])

但是我不知道用户可以为搜索字符串输入多少个单词。 有什么可能的解决方案?

我使用过eval()函数,该函数在动态生成的字符串中传递“如果document [line]中的word [0]或document [line]中的word [1]或........”在运行时,但这不起作用。我在'if'处收到语法错误。

1 个答案:

答案 0 :(得分:5)

if介绍了整个语句,而不是每个单独的条件。

if words[0] in document[line] or words[1] in document[line] or words[2] in document[line]:
    print(document[line])

这可以写得更简洁,尤其是因为您想使用words函数遍历any全部

if any(x in document[line] for x in words):
    print(document[line])

看起来您只是想遍历document的每个元素,而对索引没有特别的兴趣。

for line in document:
    if any(x in line for x in words):
        print(line)
相关问题