[英]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()
But you've already read through the whole file, so there's nothing to read anymore, thus f.readline()
returns ''
. 但是您已经阅读了整个文件,因此不再需要读取任何内容,因此f.readline()
返回''
。 Next you try to loop through each word in the line
variable, which is just ''
. 接下来,您通过在每个单词尽量循环line
变量,这仅仅是''
。
Instead of all this, you should just loop through all the lines using for line in f:
, so something like: 除了所有这些,您还应该for line in f:
使用for line in f:
遍历所有行,如下所示:
with open(file, 'r') as f:
for line in f:
line = line.lower()
for word in search:
if word in line:
print(line)
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()
). 我不确定您要使用if word == None:
做什么,因为line
是一个字符串,而word
是该字符串的一部分(您使用line.split()
),所以该单词永远不能为None
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.