读取文本文件的行并获取charmap解码错误

zwi*_*k86 2 python decode file text-files python-3.x

即时通讯使用python3.3和sqlite3数据库.我有一个大约270mb的大文本文件,我可以用Windows7中的写字板打开.

该文件中的每一行如下所示:

term\t number \n

我想读取每一行并将值保存在数据库中.我的代码如下:

f = open('sorted.de.word.unigrams', "r")
for line in f:

    #code
Run Code Online (Sandbox Code Playgroud)

我能够将所有数据读入我的数据库,但只是某一行,我建议可能是所有行的一半.然后我得到以下错误:

File "C:\projects\databtest.py", line 18, in <module>
for line in f:
File "c:\python33\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 140: character maps to   <undefined>
Run Code Online (Sandbox Code Playgroud)

我试图用encoding = utf-8打开文件,但是其他编解码器都没有用.然后我尝试通过另存为utf-8 txt文件使用写字板进行复制.但是写字板崩溃了.

这里的问题在哪里,看起来python无法处理的那一行中有一些字符.我该怎么做才能完全读取我的文件?或者是否可以忽略此类错误消息并继续下一行?

您可以在此处下载打包文件:

http://wacky.sslmit.unibo.it/lib/exe/fetch.php?media=frequency_lists:sorted.de.word.unigrams.7z

非常感谢!

Jan*_*ila 5

我检查了文件,问题的根源似乎是该文件包含至少两个编码的单词:可能是cp1252和cp850.字符0x81 ü在cp850中,但在cp1252中未定义.您可以通过捕获异常来处理这种情况,但是其他一些德语字符映射到cp1252中的有效但错误的字符.如果您对这种不完美的解决方案感到满意,请按以下步骤操作:

with open('sorted.de.word.unigrams','rb') as f: #open in binary mode
    for line in f:
        for cp in ('cp1252', 'cp850'):
            try:
                s = line.decode(cp)
            except UnicodeDecodeError:
                pass
            else:
                store_to_db(s)
                break
Run Code Online (Sandbox Code Playgroud)