【问题标题】:Python 3.6 Messy String with Unicode characters and Bytes带有 Unicode 字符和字节的 Python 3.6 凌乱字符串
【发布时间】:2019-03-23 01:08:00
【问题描述】:

所以我使用 NewsPlease 从 Common Crawl 新闻存储库中获取文章标题,但是当我获取文章标题时,它们是正常编码字符和 Unicode 字节的混合体,我无法正确编码。取其中一个头衔:

x = articles[800].title

如果我在 spyder 中调用 x,它会返回:

'Las 10 canciones m\\xc3\\xa1s populares de la semana'

当我使用 print(x) 我明白了:

Las 10 canciones m\xc3\xa1s populares de la semana

但如果尝试使用以下方法对其进行正确编码:(正如其他帖子所建议的)

x.encode('latin1').decode('utf8')

返回

'Las 10 canciones m\\xc3\\xa1s populares de la semana'

这显然是不正确的。

有人有什么建议吗?顺便说一句,我正在使用 Python 3.6

【问题讨论】:

  • 我很确定你在获取这些数据时已经搞砸了;我很难相信数据集最初包含十六进制字符的字符串表示。你是如何初始化articles的?
  • 我无法发布完整的代码,但问题是 Newsplease 的 from_warc() 方法,这是它从普通爬网 WARC 中提取数据时返回的数据格式。 Articles 只是 NewsPlease 文章对象的列表。

标签: python python-3.x python-unicode


【解决方案1】:

找到了解决办法:

x = 'this is a test of the Spanish word m\\xc3\\xa1s'
x = x.encode('latin1').decode('unicode_escape').encode('latin1').decode('utf8')
print(x)
'this is a test of the Spanish word más'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-21
    • 1970-01-01
    • 2021-03-30
    • 2012-04-08
    • 2014-12-03
    • 2011-11-12
    • 2013-06-09
    相关资源
    最近更新 更多