小编Use*_*828的帖子

Python-如何编写不同数量的“ if(条件)或if(条件)”?

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

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

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

for line in range(0,length_of_documents):
    for word in range(0,words):
        if words[word] in document[line]:
            print(document[line])
Run Code Online (Sandbox Code Playgroud)

为了克服这个问题,我需要编写如下内容:

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])
Run Code Online (Sandbox Code Playgroud)

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

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

python parsing if-statement list

0
推荐指数
1
解决办法
93
查看次数

标签 统计

if-statement ×1

list ×1

parsing ×1

python ×1