什么'我的代码错了吗?

时间:2016-12-11 21:13:00

标签: python

我试图在学校为一个项目制作一个密码破解者,但我遇到了一个问题。这是代码:

dictfile = open('c:/ScienceFairDictionaryFolder/wordsEn.txt', 'r')
DictionaryWords = dictfile.readlines()

Password = "abductors"

for x in DictionaryWords:
    if x is Password:
        print("Found it!")
    else:
        print("This password can't be guessed!")

因此,每次运行此代码时,我都会得到:

"This password can't be guessed!"

但是,我确保这个词出现在我正在使用的词典中,所以我不明白为什么密码没有被猜到。我使用的代码是否存在错误?

2 个答案:

答案 0 :(得分:1)

您需要使用代码更改两件事:使用==进行字符串比较,并通过替换它来删除换行符(\n)。

dictfile = open('wordsEn.txt', 'r')
DictionaryWords = dictfile.readlines()

Password = "abductors"

for x in DictionaryWords:
    if x.replace("\n", "") == Password:
        print("Found it!")

    else:
        print("This password can't be guessed!")

答案 1 :(得分:1)

逐步描述建议的方法:

  1. 使用read()方法而不是readlines()来阅读文件内容。
  2. 使用split()方法生成单词列表。这也会删除换行符。
  3. 通过in运算符检查密码是否在字典中。这允许您摆脱for循环。
  4. 这段代码应该完成工作:

    with open('c:/ScienceFairDictionaryFolder/wordsEn.txt', 'r') as dictfile:
        DictionaryWords = dictfile.read().split('\n')
    
    Password = "abductors"
    
    if Password in DictionaryWords:
        print("Found it!")
    else:
        print("This password can't be guessed!")