如何打开带有utf-8非编码字符的文件?

问题描述 投票:0回答:2

我想在 python 中打开一个文本文件 (.dat),但出现以下错误: “utf-8”编解码器无法解码位置 4484 中的字节 0x92:起始字节无效 但该文件是使用utf-8编码的,所以可能有一些字符无法读取。我想知道,有没有办法在不调用每个奇怪字符的情况下处理这个问题?因为我有一个相当大的文本文件,需要几个小时才能找到非编码的 Utf-8 编码字符。

这是我的代码

import codecs
f = codecs.open('compounds.dat', encoding='utf-8')
for line in f:
    if "InChI=1S/C11H8O3/c1-6-5-9(13)10-7(11(6)14)3-2-4-8(10)12/h2-5" in line:
        print(line)
searchfile.close()
python encoding utf-8 character-encoding
2个回答
11
投票

不应该“花费几个小时”来找到坏字节。该错误告诉您确切地它在哪里;它位于输入中的索引 4484,值为

0x92
;如果你这样做了:

with open('compounds.dat', 'rb') as f:
    data = f.read()

无效字节位于

data[4484]
,您可以根据需要进行切片以找出其周围的内容。

无论如何,如果您只想忽略或替换无效字节,这就是

errors
参数的用途。 使用
io.open
(因为
codecs.open
在很多方面都被巧妙地破坏了,而
io.open
既更快又更正确):

# If this is Py3, you don't even need the import, just use plain open which is
# an alias for io.open
import io

with io.open('compounds.dat', encoding='utf-8', errors='ignore') as f:
    for line in f:
        if u"InChI=1S/C11H8O3/c1-6-5-9(13)10-7(11(6)14)3-2-4-8(10)12/h2-5" in line:
            print(line)

将忽略无效字节(将它们丢弃,就好像它们从未存在一样)。您还可以传递

errors='replace'
为每个垃圾字节插入替换字符,这样您就不会默默地删除数据。

在这种情况下,

0x92
的cp1252编码,所以你的文件很可能是cp1252,忽略错误是错误的解决方案,你应该使用正确的编码,将
with
语句更改为:

with io.open('compounds.dat', encoding='cp1252') as f:

2
投票

如果处理大量数据,最好使用默认编码,如果错误仍然存在,则也使用errors =“ignore”

with open("filename" , 'r'  , encoding="utf-8",errors="ignore") as f:
    f.read()
© www.soinside.com 2019 - 2024. All rights reserved.