我试图用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()函数,它在字符串中传递,动态生成“if word in documentline or if words1 in documentline or........”在运行时,但这不起作用。我在'if‘处遇到语法错误。
发布于 2019-04-01 01:53:24
if引入了整个语句,而不是每个单独的条件。
if words[0] in document[line] or words[1] in document[line] or words[2] in document[line]:
print(document[line])这可以写得更简洁,特别是因为您希望使用any函数遍历所有words。
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)https://stackoverflow.com/questions/55443749
复制相似问题