【问题标题】:how can i search a text file of list of words from user input and print the line which contains these words?如何从用户输入中搜索单词列表的文本文件并打印包含这些单词的行?
【发布时间】:2015-09-21 09:40:52
【问题描述】:

我的查询是我想从文本文件中搜索单词并打印包含这些单词的行。所有单词都作为用户输入给出。 不知何故,我到达了这一点,它的输出什么都没有。

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('')

【问题讨论】:

  • word 永远不会是 None:它是一个字符串。
  • 在检查 word in line 之前是否尝试过打印每个单词(和行)?
  • def http(y): for line in file2: if re.search('401',line) or re.search('HTTP/1.1',line): print(line), if行 == 无:打印('')

标签: python file python-3.x


【解决方案1】:

您正在读取所有行并将它们保存到变量中:

lines = f.readlines()

然后你尝试再读一行:

line = f.readline()

但是您已经阅读了整个文件,所以没有什么要阅读的了,因此f.readline() 返回''。 接下来,您尝试遍历 line 变量中的每个单词,即 ''

您应该使用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)

我不确定你想用if word == None: 做什么,这个词永远不能是None,因为line 是一个字符串,而word 是该字符串的一部分(你使用了@987654333 @)。

【讨论】:

  • 如果我使用上面的代码,它会打印整个文件而不是包含用户输入的单词的行。
  • @RAM 看到这个古老的答案,如果它适合你,你应该考虑接受它! :)
猜你喜欢
  • 2021-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多