使用Python3处理UTF-8文件中的编码错误

bivouac0

我正在尝试使用语料库来训练ML模型,但是我遇到了一些编码错误,该错误很可能是由其他人的文件转换/注释引起的。在打开文件时,我可以从视觉上看到错误,vim但是python在阅读时似乎没有注意到它们。语料库相当大,因此我需要找到一种方法来让python检测它们,并希望有一种纠正它们的方法。

这是在vim...中查看的示例行

# ::snt That<92>s what we<92>re with<85>You<92>re not sittin<92> there in a back alley and sayin<92> hey what do you say, five bucks?

<92>应该是撇号,而<85>应该是3个点。其他行上还显示许多其他值。进行一些谷歌搜索,我认为原始编码可能是CP1252,但是目前fileLinux下命令将此文件列为UTF-8。我尝试了几种方法来打开它,但是没有运气...

with open(fn) as f: 退货

# ::snt Thats what were withYoure not sittin there in a back alley and sayin hey what do you say, five bucks?

这会跳过这些标记并连接单词,这是一个问题。

with open(fn, encoding='CP1252') as f: 退货

# ::snt ThatA's what weA're withA...YouA're not sittinA' there in a back alley and sayinA' hey what do you say, five bucks?

在视觉上为那些奇数字符插入“ A”。

with io.open(fn, errors='strict') 不会产生任何错误,也不会读取字节流并进行解码,因此不幸的是,在这一点上,我什至无法检测到错误程度不大的错误。

有没有一种方法可以读取这个大文件并检测其中的编码错误。更好的是,有没有办法纠正它们?

马克·托洛宁

使用答案中的原始数据,您可以通过双重编码获得mojibake。您需要进行两次解码才能正确翻译。

>>> s = b'# ::snt That\xc2\x92s what we\xc2\x92re with\xc2\x85You\xc2\x92re not sittin\xc2\x92 there in a back alley and sayin\xc2\x92 hey what do you say, five bucks?\n'
>>> s.decode('utf8').encode('latin1').decode('cp1252')
'# ::snt That’s what we’re with…You’re not sittin’ there in a back alley and sayin’ hey what do you say, five bucks?\n'

数据实际上是UTF-8,但是在解码为Unicode时,错误的代码点是Windows-1252代码页的字节.encode('latin1')转换的Unicode码点1:1回字节,由于latin1编码是Unicode的前256个码点,那么它可以被正确地与Windows 1252解码。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章