1

我一直在尝试创建一个程序,该程序接受输入并检查该输入是否在文件中的某些文本中。我的最终目标是创建一个用户登录 GUI,但我不会在这里显示 GUI 的代码,因为有很多。我需要弄清楚如何比较输入和文件中的文本。到目前为止,这是我的代码

def check(entry):
    search = open('password.txt', 'r')
    if str(entry) in str(search): 
        return (entry, "Word found")
    else:
        return entry, ("Word not found")

with open('password.txt', 'r') as text:
    print (text.read())

while True:
    entry=input("\nSearch for word: ")
    print(check(entry)) 

当我运行代码时,它会说 1、2、5 和 12 都在文本中,但没有确认文本中的单词。如果有人可以提供帮助,将不胜感激,谢谢。

4

1 回答 1

1

忽略另一条评论中涉及的安全性坏主意, str(search) 不像您想象的那样工作。如果您打印它,您应该会看到如下内容:

<open file 'password.txt', mode 'r' at 0x0000000001EB2810>

这是您使用 open 函数创建的对象的描述。您需要先使用 .read() 方法将文件读入字符串。

于 2014-10-20T18:30:48.013 回答