Python:为什么我会收到NameError?

时间:2012-11-24 02:22:44

标签: python

我有以下代码:

from crypt import crypt
import itertools
from string import ascii_letters, digits

def decrypt(all_hashes, salt, charset=ascii_letters + digits + "-"):
     products = (itertools.product(charset, repeat=r) for r in range(8))
     chain = itertools.chain.from_iterable(products)
     for candidate in chain:
         hash = crypt(candidate, salt)
         if hash in all_hashes:
              yield candidate, hash
              all_hashes.remove(hash)
              if not all_hashes:
                 return

all_hashes = 'aaRrt6qwqR7xk', 'aaacT.VSMxhms' , 'aaWIa93yJI9kU', /
'aakf8kFpfzD5E', 'aaMOPiDnXYTPE', 'aaz71s8a0SSbU', 'aa6SXFxZJrI7E', /
'aa9hi/efJu5P.', 'aaBWpr07X4LDE', 'aaqwyFUsGMNrQ', 'aa.lUgfbPGANY', /
'aaHgyDUxJGPl6', 'aaTuBoxlxtjeg', 'aaluQSsvEIrDs', 'aajuaeRAx9C9g', /
'aat0FraNnWA4g', 'aaya6nAGIGcYo', 'aaya6nAGIGcYo', 'aawmOHEectP/g', /
'aazpGZ/jXGDhw', 'aadc1hd1Uxlz.', 'aabx55R4tiWwQ', 'aaOhLry1KgN3.', /
'aaGO0MNkEn0JA', 'aaGxcBxfr5rgM', 'aa2voaxqfsKQA', 'aahdDVXRTugPc', /
'aaaLf47tEydKM', 'aawZuilJMRO.w', 'aayxG5tSZJJHc', 'aaPXxZDcwBKgo', /
'aaZroUk7y0Nao', 'aaZo046pM1vmY', 'aa5Be/kKhzh.o', 'aa0lJMaclo592', /
'aaY5SpAiLEJj6', 'aa..CW12pQtCE', 'aamVYXdd9MlOI', 'aajCM.48K40M.', /
'aa1iXl.B1Zjb2', 'aapG.//419wZU'


all_hashes = set(all_hashes)
salt = 'aa'
for candidate, hash in decrypt(all_hashes, salt):
     print 'Found', hash, '! The original string was', candidate

当我去运行它时,我得到以下回溯错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in decrypt
NameError: must be string, not tuple

我认为它与我的“all_hashes”变量有关,但是如果我取出逗号,则所有不同的哈希值都存储为一个长字符串

有人请提前了解一下

1 个答案:

答案 0 :(得分:3)

product是元组,如

('g', 'g', 'g', 'e', 'a', 'b', 'f')

crypt需要一个字符串。

在将元组传递给crypt

之前将其转换为字符串
 for candidate in chain:
     hash = crypt((''.join(candidate)), salt)

(感谢Joel Cornett对字符串进行了很好的转换,并感谢HVNSweeting进行了改进。)