【问题标题】:ascii decode error even though everything being unicode ( python 2.7)即使一切都是 unicode(python 2.7),ascii 解码错误
【发布时间】:2019-06-19 06:31:02
【问题描述】:

我在数据流 (apache beam) 中运行一个脚本,它在 python 2.7.12 中运行,并使用 unicode 字符串进行一些文本处理。

在处理中,我执行以下操作,其中 nounphrase 是 unicode(我认为...)

# -*- coding: utf-8 -*-
...
key = u"{}_{}".format(
    noun, phrase.replace(u" ", u"_")
)

但是它会产生 ascii 解码错误

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

我可以进行调试并获取用作 nounphrase 的字符串的代表,但我目前没有它们,因为我的日志没有输出他们。

我不明白 ascii 解码错误,当我认为我非常明确我想要 unicode 中的所有内容时!

您能否提供一些提示,或者我应该返回有关输入字符串的更多信息?

【问题讨论】:

  • nounphrase 是什么?听起来phrase 有字符0xe2。在 latin1 中,这是一个 â,它不是真正的 ascii 字符。
  • 但是当我明确地创建一个 unicode 字符串 @FHTMitchell 时这有关系吗
  • 是的——python只自动编码ascii
  • 你如何创建名词和短语?
  • nounphrase 或两者都不是 Unicode 字符串。 .decode() 他们首先使用正确的编解码器。 Python 2 将尝试自动将字节字符串解码为 Unicode 字符串,但将使用 ascii 编解码器。 Python 3 不会自动尝试,所以你会立即发现错误,即使字符串是 ASCII-only。

标签: python python-2.7 unicode dataflow


【解决方案1】:

好的,所以你的字符串中有一个非 ascii 字符。需要将phrase直接转成unicode

 phrase.decode('latin-1')

unicode.format进行操作之前

【讨论】:

    【解决方案2】:

    一位同事提醒我,我总是可以将整个输出解码,在这种情况下,这是我选择的任何格式的关键。

    key = u"{}_{}_{}_{}".format(
         business_unit_id, date, noun, phrase.replace(u" ", u"_")
        ).encode('ascii', 'ignore')
    

    在这种情况下,我想要 ascii 输出,而不关心缺少像?这样的字符。

    如果我想要 unicode 格式的输出,我也可以使用 ...).encode('utf-8')

    在我的情况下,我使用 ascii 输出解决了问题,因为 apache Beam 中的管道似乎对其映射减少管道中的 unicode 键不满意

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-03
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多