【问题标题】:Converting a weird data type to Str将奇怪的数据类型转换为 Str
【发布时间】:2016-01-14 14:53:38
【问题描述】:

我提前道歉,因为我不知道如何问这个!好的,所以我正在尝试在 Python 中使用 twitter API。这是给我问题的代码的 sn-p:

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 时,解释器告诉我无法对 Trend 对象进行编码。我该如何解决这个问题?

【问题讨论】:

  • 您使用的是 Python 2 还是 Python 3? print trends 怎么样?
  • 当我尝试“打印趋势”时,我收到与上述类似的错误! UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-5: ordinal not in range(128) This is within python 2.7
  • 你能把你的编码从 UTC-8 改成 Unicode 吗?我怀疑你里面有一个不标准的角色。
  • @Prune 你的意思是使用 .encode 吗?
  • 这是一种方式。还有编译器指令为整个运行指定 Unicode,因此您不必对每个不适合 ASCII 模型的字符进行编码。

标签: python type-conversion python-twitter


【解决方案1】:

简单回答:

使用repr,而不是str。它应该始终、始终有效(除非 API 本身已损坏并且这是引发错误的地方)。

长答案:

默认情况下,当您在 Python 2 中将 Unicode 字符串转换为字节 str(反之亦然)时,它将默认使用 ascii 编码进行转换过程。这在大多数情况下都有效,但并非总是如此。因此,像这样令人讨厌的边缘情况是一种痛苦。 Python 3 向后兼容性中断的主要原因之一是改变了这种行为。

使用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 数据;它几乎是网络上所有的默认编码。

【讨论】:

  • ThePentium 上面的回答奏效了。我的 IDE 没有使用正确的编码格式。不过感谢您的提示!
猜你喜欢
  • 2017-08-18
  • 2014-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多