2017-07-29 70 views
1

我在Python 3.5.3中编写了一个脚本,它从文件中获取用户名/密码组合并将它们写入另一个文件。该脚本是用Windows 10在机器上编写的,并且工作正常。但是,当我试图在运行Yosemite的MacBook上运行脚本时,出现了与ASCII编码有关的错误。UnicodeDecodeError:'ascii'编解码器无法解码位置2370中的字节0xaa:序号不在范围内(128)

相关的功能是这样的:

def buildDatabase(): 
     print("Building database, this may take some time...") 
     passwords = open("10-million-combos.txt", "r") #File with user/pword combos. 
     hashWords = open("Hashed Combos.txt", "a") #File where user/SHA-256 encrypted pwords will be stored. 
     j = 0 
     hashTable = [[ None ] for x in range(60001)] #A hashtable with 30,000 elements, quadratic probing means size must = 2 x the final size + 1 
     for line in passwords: 
       toSearch = line 
       i = q = toSearch.find("\t") #The username/pword combos are formatted: username\tpassword\n. 
       n = toSearch.find("\n") 
       password = line[i:n-1] #i is the start of the password, n is the end of it 
       username = toSearch[ :q] + ":" #q is the end of the username 
       byteWord = password.encode('UTF-8') 
       sha.update(byteWord) 
       toWrite = sha.hexdigest() #password is encrypted to UTF-8, run thru SHA-256, and stored in toWrite 
       skip = False 
       if len(password) == 0: #if le(password) is 0, just skip it 
         skip = True 
       if len(password) == 1: 
         doModulo = ord(password[0]) ** 4 
       if len(password) == 2: 
         doModulo = ord(password[0]) * ord(password[0]) * ord(password[1]) * ord(password[1]) 
       if len(password) == 3: 
         doModulo = ord(password[0]) * ord(password[0]) * ord(password[1]) * ord(password[2]) 
       if len(password) > 3: 
         doModulo = ord(password[0]) * ord(password[1]) * ord(password[2]) * ord(password[3]) 
       assignment = doModulo % 60001 
       #The if block above gives each combo an assignment number for a hash table, indexed by password because they're more unique than usernames 
       successful = False 
       collision = 0 

的错误如下:

Traceback (most recent call last): 
    File "/Users/connerboehm/Documents/Conner B/PythonFinalProject.py", line 104, in <module> 
    buildDatabase() 
    File "/Users/connerboehm/Documents/Conner B/PythonFinalProject.py", line 12, in buildDatabase 
    for line in passwords: 
    File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py", line 26, in decode 
    return codecs.ascii_decode(input, self.errors)[0] 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xaa in position 2370: ordinal not in range(128) 

这里发生了什么?我在Windows上没有收到过这个错误,而且我没有看到我尝试编码为UTF-8的任何问题。

编辑:记事本编码ANSI。更改编码(只是将数据复制并粘贴到新的.txt文件)为UTF-8解决了这个问题。

+0

学习字符编码(如ASCII和unicode)的时候,UTF-8是一个很好的开始。 – zaph

回答

2

你的程序没有说明在文件"10-million-combos.txt"中使用了什么编解码器,所以Python在这种情况下试图将它解码为ASCII。 0xaa不是ASCII顺序,因此失败。确定您的文件中使用了哪种编解码器,并通过open的参数encoding

+0

“确定文件中使用的编解码器”说起来容易做起来难。也许你可以建议一种方法来做到这一点,比如[chardet](https://pypi.python.org/pypi/chardet)模块? –

相关问题