【问题标题】:How can I get my Python to parse the following text?如何让我的 Python 解析以下文本?
【发布时间】:2013-06-21 23:00:12
【问题描述】:

我有一个文本示例:

"PROTECTING-ħarsien",

我正在尝试使用以下内容进行解析

import csv, json

with open('./dict.txt') as maltese:
    entries = maltese.readlines()
    for entry in entries:
        tokens = entry.replace('"', '').replace(",", "").replace("\r\n", "").split("-")
        if len(tokens) == 1:
            pass
        else:   
            print tokens[0] + "," + unicode(tokens[1])

但我收到一条错误消息

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0: ordinal not in range(128)

我做错了什么?

【问题讨论】:

    标签: python ascii python-unicode


    【解决方案1】:

    dict.txt 似乎是 UTF-8 编码的(ħ 在 UTF-8 中是 0xc4 0xa7)。

    你应该open the file as UTF-8,然后:

    import codecs
    with codecs.open('./dict.txt', encoding="utf-8") as maltese:
        # etc.
    

    然后您将使用 Unicode 字符串而不是字节字符串;因此,您不需要对它们调用 unicode(),但您可能需要将它们重新编码为您要输出到的终端的编码。

    【讨论】:

    • 我已经尝试过这个建议,但仍然遇到同样的错误。还有什么我可能做错的吗?
    • 在输出之前,您是否将字符串重新编码为终端的编码?
    【解决方案2】:

    您必须将最后一行更改为(已经过测试可以处理您的数据):

    print tokens[0] + "," + unicode(tokens[1], 'utf8')
    

    如果你没有那个utf8,Python 会假定源是ascii 编码,因此会出现错误。

    http://docs.python.org/2/howto/unicode.html#the-unicode-type

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2019-07-05
      • 2015-07-10
      相关资源
      最近更新 更多