python无法编码奇怪的字符

我正在尝试通过运行以下脚本来解析txt文件> 2GB:


#!/usr/bin/env python

import json


def convert2json(filename):

    with open(filename) as I:

        for line in I:

            d = {"data": line}

            print(json.dumps(d, ensure_ascii=False))


if __name__ == "__main__":

    import sys


    convert2json(sys.argv[1])

脚本抛出错误:


Traceback (most recent call last):

  File "ori.py", line 13, in <module>

    convert2json(sys.argv[1])

  File "ori.py", line 8, in convert2json

    print(json.dumps(d))

  File "/usr/lib/python2.7/json/__init__.py", line 244, in dumps

    return _default_encoder.encode(obj)

  File "/usr/lib/python2.7/json/encoder.py", line 207, in encode

    chunks = self.iterencode(o, _one_shot=True)

  File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode

    return _iterencode(o, 0)

UnicodeDecodeError: 'utf8' codec can't decode byte 0xe0 in position 31: invalid continuation byte

并且在处理特殊字符时失败(我相信):


<E0>ทำคาม:

:<E9>皇甫

:<E9>皇甫:<E9>皇甫:<E9>皇甫

如何使脚本仅忽略引起问题的行?


当我转到要解析的文件并复制无法处理的大部分行时,请创建一个新文件并再次运行该脚本-它将起作用。我通过使用来复制行,less而不是将行复制到文件中vi。复制带有编码本身的行时,我是否正在做某些事情?


侃侃尔雅
浏览 197回答 2
2回答

小怪兽爱吃肉

好的,您正在使用Python 2,因此从文件中读取的是字节字符串。更根据错误信息,您对默认ensure_ascii参数为true。在这种情况下,所有字符串都将使用默认编码(utf8)进行解码。如果您输入的不是utf8编码,则会得到一个UnicodeDecodeError。该怎么办?如果您不确定初始编码,只想保留所有内容,则可以声明Latin1编码。它只是更改具有该代码的unicode字符中的每个字节。的ensure_ascii是有点不同的:它只是允许在所得到的JSON字符串,其可导致非便携式的Json任何字节:RFC没有明确禁止包含不与有效Unicode字符相对应的字节序列的JSON字符串(例如,未配对的UTF-16替代),但是它确实指出它们可能会导致互操作性问题。默认情况下,此模块接受并输出此类序列的代码点(如果存在于原始str中)。因此,这是一种防弹方式:def convert2json(filename):&nbsp; &nbsp; with open(filename) as I:&nbsp; &nbsp; &nbsp; &nbsp; for line in I:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; d = {"data": line}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(json.dumps(d, encoding='Latin1'))只是输入文件中的一个非ascii字符,例如'\x..',将在Json中编码为'\u00..'

慕姐8265434

好吧,要跳过这些行,您可以使用以下命令:#!/usr/bin/env pythonimport jsondef convert2json(filename):&nbsp; &nbsp; with open(filename) as I:&nbsp; &nbsp; &nbsp; &nbsp; for line in I:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; d = {"data": line}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(json.dumps(d, ensure_ascii=False))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; except:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continueif __name__ == "__main__":&nbsp; &nbsp; import sys&nbsp; &nbsp; convert2json(sys.argv[1])&nbsp;&nbsp;我已经将代码包装在try / except块中的循环中。这样,当发生错误时,它将被忽略。您将不会从当前行看到任何输出,并且脚本将继续进行到下一行。但是,尝试使用文件的提供的部分时,我的测试没有引发错误。您能告诉我们文件的编码是什么吗?您确定问题是由这些字符引起的吗?尝试print()在原始代码和计数器中添加一条 语句,以便标识正确的无效行。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python