gpt4 book ai didi

python - 检查文本文件中的数据

转载 作者:太空宇宙 更新时间:2023-11-03 18:08:08 27 4
gpt4 key购买 nike

我一直在尝试创建一个程序,该程序接受输入并检查该输入是否在文件中的某些文本中。我的最终目标是创建一个用户登录 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 都在文本中,但文本中的单词都没有得到确认。如果有人可以提供帮助,我们将不胜感激。

最佳答案

忽略另一条评论中涉及的安全不良想法,str(search) 并不像您想象的那样工作。如果打印它,您应该看到类似以下内容:

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

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

关于python - 检查文本文件中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26472068/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com