转换奇怪的数据类型

2024-09-29 22:34:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我事先道歉,因为我不知道怎么问这个!好的,所以我尝试在Python中使用twitterapi。下面是给我带来问题的代码片段:

trends = twitter.Api.GetTrendsCurrent(api)
print str(trends)

这将返回:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-5: ordinal not in range(128)

当我尝试.encode时,解释器告诉我不能对趋势对象进行编码。我该怎么办?你知道吗


Tags: 代码inapiasciitwittercancodecencode
1条回答
网友
1楼 · 发布于 2024-09-29 22:34:08

简单回答:

使用repr,而不是str。它应该总是,总是工作的(除非API本身被破坏了,而这正是抛出错误的地方)。你知道吗

长答案:

默认情况下,在python2中将Unicode字符串转换为byte str(反之亦然)时,转换过程将默认使用ascii编码。这在大多数情况下都有效,但并不总是有效。因此,像这样令人讨厌的边缘案件是一种痛苦。Python3中向后兼容性中断的一个重要原因是改变了这种行为。你知道吗

使用latin1进行测试。它可能不是正确的编码,但它将始终(总是,总是,总是)工作,并为您提供一个正确调试的起点,这样您至少可以打印一些东西。你知道吗

trends = twitter.Api.GetTrendsCurrent(api)
print type(trends)
print unicode(trends)
print unicode(trends).encode('latin1')

或者,更好的是,当编码强制它忽略或替换错误时:

trends = twitter.Api.GetTrendsCurrent(api)
print type(trends)
print unicode(trends)
print unicode(trends).encode('utf8', 'xmlcharrefreplace')

很有可能,因为您处理的是基于web的API,所以您处理的是UTF-8数据;它几乎是web上所有的默认编码。你知道吗

相关问题 更多 >

    热门问题