我事先道歉,因为我不知道怎么问这个!好的,所以我尝试在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时,解释器告诉我不能对趋势对象进行编码。我该怎么办?你知道吗
简单回答:
使用
repr
,而不是str
。它应该总是,总是工作的(除非API本身被破坏了,而这正是抛出错误的地方)。你知道吗长答案:
默认情况下,在python2中将Unicode字符串转换为byte str(反之亦然)时,转换过程将默认使用
ascii
编码。这在大多数情况下都有效,但并不总是有效。因此,像这样令人讨厌的边缘案件是一种痛苦。Python3中向后兼容性中断的一个重要原因是改变了这种行为。你知道吗使用
latin1
进行测试。它可能不是正确的编码,但它将始终(总是,总是,总是)工作,并为您提供一个正确调试的起点,这样您至少可以打印一些东西。你知道吗或者,更好的是,当编码强制它忽略或替换错误时:
很有可能,因为您处理的是基于web的API,所以您处理的是UTF-8数据;它几乎是web上所有的默认编码。你知道吗
相关问题 更多 >
编程相关推荐