【问题标题】:Searching for keyword in text file在文本文件中搜索关键字
【发布时间】:2016-12-22 02:22:07
【问题描述】:

我在一个名为“SortedUniqueMasterList.txt”的文本文件中有一个密码列表。我正在编写一个程序,它接受用户输入并检查输入的密码是否在列表中。

这是我的代码:

Passwords = []

with open("SortedUniqueMasterList.txt", "r", encoding = "latin-1") as infile:
    print("File opened.")
    for line in infile:
        Passwords.append(line)
    print("Lines loaded.")

while True:
    InputPassword = input("Enter a password.")
    print("Searching for password.")
    if InputPassword in Passwords:
        print("Found")
    else:
        print("Not found.")

但是,我输入的每个密码都返回“未找到。”,即使是我确定的密码也在列表中。

我哪里出错了?

【问题讨论】:

  • 你能否提供一条线的样子?用户输入会是什么?
  • Passwords.append(line.strip()) 对我有用
  • @downshift:您应该将其发布为答案。
  • @BrenBarn,好吧,虽然我看到用户因为单线修复而受到抨击,所以我只是犹豫不决
  • 现在正在处理这个问题,但是请在您的 while 语句之前打印行列表的样子

标签: python python-3.x search text


【解决方案1】:

在读取文件中的行之后,Passwords 列表中的每个条目都将包含一个“换行”字符 '\n',您需要在检查匹配之前将其删除,str.strip() 应该允许关键字可以这样找到:

for line in infile:
        Passwords.append(line.strip())

【讨论】:

    【解决方案2】:

    更接近这个运行 - 当您读取文件时,您可以将每一行作为数组元素读取。试试这个,让我知道它是怎么回事

    with open("SortedUniqueMasterList.txt", "r") as infile:
        print("File opened.")
        Passwords = infile.readlines()
        print("Lines loaded.")
    
    while True:
        InputPassword = input("Enter a password.")
        InputPassword  = str(InputPassword)
        print("Searching for password.")
        if InputPassword in Passwords:
            print("Found")
        else:
            print("Not found.")
    

    【讨论】:

      【解决方案3】:

      问题是您无法在 python 列表中查找子字符串。您必须遍历列表检查是否在任何元素中找到子字符串,然后确定是否找到它。

      Passwords = []
      
      with open("SortedUniqueMasterList.txt", "r", encoding = "latin-1") as infile:
          print("File opened.")
          for line in infile:
              Passwords.append(line)
          print("Lines loaded.")
      
      while True:
          InputPassword = input("Enter a password.")
          print("Searching for password.")
          found = False
          for i in Passwords:
              if InputPassword in i:
                  found = True
                  break
          if found:
              print("Found.")
          else:
              print("Not found.")
      

      【讨论】:

      • 他不是在寻找子字符串,而是在查看密码是否在密码列表中。
      • 没错,他需要获取 infile 以返回字符串列表,但在任何 pt 处都没有查看单个字符串
      【解决方案4】:

      我认为这是我遇到的问题,也许是,也许不是。该问题称为尾随换行符。基本上,当您在文本文档上按 Enter 键时,它会输入一个特殊字符,表示它是一个新行。要摆脱这个问题,请导入模块linecache。然后,您不必打开文件并关闭它,而是执行linecahce.getline(file, line).strip()。 希望这会有所帮助!

      【讨论】:

      • 您的诊断是正确的,但您提出的解决方案不是正确的处理方法。
      猜你喜欢
      • 2015-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多