在文本文件中查找单词
Find word in text file
我试图为自己创建一个小密码破解程序。
问题是程序总是告诉我:Password not found!
我使用一行只有一个单词的文本文件!
pw = "password"
# The password in the list is "password"
pwlist = open('passwordlist.txt', 'r')
words = pwlist.readlines()
found = False
for password in words:
if str(password) == pw:
print(password)
found = True
break
if found == True:
print("password found!")
else:
print("Password not found!")
这段代码看起来应该可以正常工作...您能否确认 .txt
文件中的单词确实是 "password"(拼写方式相同,没有多余的 characters/blank空格等) ?
方法 readlines()
不会从行中删除尾部回车 returns。尝试
if password.strip() == pw:
readline()
方法在每行的末尾提取换行符 \n
(新行转义序列)。
你会注意到,如果你打开你的文本文件,它实际上是两行,第二行只有 0
.
因此,要完成这项工作,您需要替换:
words = pwlist.readlines()
有了这个:
words = [line.rstrip('\n') for line in pwlist]
我试图为自己创建一个小密码破解程序。
问题是程序总是告诉我:Password not found!
我使用一行只有一个单词的文本文件!
pw = "password"
# The password in the list is "password"
pwlist = open('passwordlist.txt', 'r')
words = pwlist.readlines()
found = False
for password in words:
if str(password) == pw:
print(password)
found = True
break
if found == True:
print("password found!")
else:
print("Password not found!")
这段代码看起来应该可以正常工作...您能否确认 .txt
文件中的单词确实是 "password"(拼写方式相同,没有多余的 characters/blank空格等) ?
方法 readlines()
不会从行中删除尾部回车 returns。尝试
if password.strip() == pw:
readline()
方法在每行的末尾提取换行符 \n
(新行转义序列)。
你会注意到,如果你打开你的文本文件,它实际上是两行,第二行只有 0
.
因此,要完成这项工作,您需要替换:
words = pwlist.readlines()
有了这个:
words = [line.rstrip('\n') for line in pwlist]