如何从用户输入中搜索单词列表的文本文件并打印包含这些单词的行? [英] how can i search a text file of list of words from user input and print the line which contains these words?
问题描述
我在这里的查询是我想从文本文件中搜索单词并打印包含这些单词的行.所有单词均作为用户输入给出. 我一直以某种方式达到了这一点,直到没有输出为止.
My query here is I want to search words from a text file and print those lines which contain those words. All the words are given as user input. Somehow I reached till this point it's is giving output as nothing.
def sip(x):
print("====Welcome to SIP log Debugger ==== ")
file= input("Please Enter log File path: ")
search = input("Enter the Errors you want to search for(seperated with commas): ")
search = [word.strip() for word in search.lower().split(",")]
with open(file,'r') as f:
lines = f.readlines()
line = f.readline()
for word in line.lower().split():
if word in line:
print(line),
if word == None:
print('')
推荐答案
您正在读取所有行并将其保存到变量中:
You're reading all the lines and saving them into a variable:
lines = f.readlines()
然后,您尝试再读一行:
Then you try to read one more line:
line = f.readline()
但是您已经读完了整个文件,因此不再需要读取任何内容,因此f.readline()
返回''
.
接下来,您尝试遍历line
变量(即''
)中的每个单词.
But you've already read through the whole file, so there's nothing to read anymore, thus f.readline()
returns ''
.
Next you try to loop through each word in the line
variable, which is just ''
.
代替所有这些,您应该使用for line in f:
遍历所有行,如下所示:
Instead of all this, you should just loop through all the lines using for line in f:
, so something like:
with open(file, 'r') as f:
for line in f:
line = line.lower()
for word in search:
if word in line:
print(line)
我不确定您要使用if word == None:
做什么,这个词永远不能是None
,因为line
是字符串,而word
是该字符串的一部分(您使用了
I'm not sure what you're trying to do with the if word == None:
, the word can never be None
since line
is a string and word
is part of that string (you used line.split()
).
这篇关于如何从用户输入中搜索单词列表的文本文件并打印包含这些单词的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!