ascii 解码错误,即使一切都是 unicode ( python 2.7)
ascii decode error even though everything being unicode ( python 2.7)
我是 运行 数据流 (apache beam) 中的一个脚本,它在 python 2.7.12 中运行,并使用 unicode 字符串进行一些文本处理。
在处理过程中,我执行以下操作,其中 noun 和 phrase 是 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)
我可以进行调试并获得在 noun 和 phrase 中使用的字符串的 repr,但我目前没有它们是因为我的日志记录没有输出它们。
我不明白 ascii 解码错误,当我认为我非常具体我想要 unicode 中的所有内容时!
你能给一些提示吗?或者我应该回来提供有关输入字符串的更多信息吗?
好的,所以你的字符串中有一个非 ascii 字符。需要直接把phrase
转成unicode
phrase.decode('latin-1')
在 unicode.format
中进行操作之前
一位同事提醒我,我总是可以将整个输出(在本例中是密钥)解码为我选择的任何格式。
key = u"{}_{}_{}_{}".format(
business_unit_id, date, noun, phrase.replace(u" ", u"_")
).encode('ascii', 'ignore')
在这种情况下,我想要 ascii 输出而不关心丢失的字符,如 .
如果我想要 unicode 输出,我也可以使用 ...).encode('utf-8')
。
在我的例子中,我选择了 ascii 输出,因为 apache beam 中的管道似乎对其 map reduce 管道中的 unicode 键不满意
我是 运行 数据流 (apache beam) 中的一个脚本,它在 python 2.7.12 中运行,并使用 unicode 字符串进行一些文本处理。
在处理过程中,我执行以下操作,其中 noun 和 phrase 是 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)
我可以进行调试并获得在 noun 和 phrase 中使用的字符串的 repr,但我目前没有它们是因为我的日志记录没有输出它们。
我不明白 ascii 解码错误,当我认为我非常具体我想要 unicode 中的所有内容时!
你能给一些提示吗?或者我应该回来提供有关输入字符串的更多信息吗?
好的,所以你的字符串中有一个非 ascii 字符。需要直接把phrase
转成unicode
phrase.decode('latin-1')
在 unicode.format
一位同事提醒我,我总是可以将整个输出(在本例中是密钥)解码为我选择的任何格式。
key = u"{}_{}_{}_{}".format(
business_unit_id, date, noun, phrase.replace(u" ", u"_")
).encode('ascii', 'ignore')
在这种情况下,我想要 ascii 输出而不关心丢失的字符,如 .
如果我想要 unicode 输出,我也可以使用 ...).encode('utf-8')
。
在我的例子中,我选择了 ascii 输出,因为 apache beam 中的管道似乎对其 map reduce 管道中的 unicode 键不满意