简体   繁体   English

在文本文件中查找单词

[英]Find word in text file

I tried to create a little password cracker just for myself. 我试图为自己创建一个小的密码破解程序。 The problem is that the program always tells me: Password not found! 问题是该程序总是告诉我: Password not found! I use a text file with just one word in a line! 我在一行中只使用一个单词的文本文件!

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文件中的单词确实是“密码”(拼写相同,没有多余的字符/空格等)吗?

The method readlines() doesn't strip trailing carriage returns from the lines. 方法readlines()不会从行中删除尾随回车符。 Try 尝试

if password.strip() == pw: 

The readline() method picks up the newline character at the end of each line \\n (new line escape sequence). readline()方法在每行\\n (新行转义序列)的末尾拾取换行符。

You'll notice that if you open your text file it is actually two lines, the second line just has length 0 . 您会注意到,如果打开文本文件,实际上是两行,第二行的长度为0

So to make this work, you'll need to replace: 因此,要使其正常工作,您需要替换:

words = pwlist.readlines()

With this: 有了这个:

words = [line.rstrip('\n') for line in pwlist]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM