【问题标题】:encoding/decoding unicode and utf-8 : Python [duplicate]编码/解码unicode和utf-8:Python [重复]
【发布时间】:2013-05-11 07:13:09
【问题描述】:

我有一个 html 文本:If I'm reading lots of articles

我正在尝试将 ' 和其他此类特殊字符替换为 unicode '。我做了

rawtxt.encode('utf-8').encode('ascii','ignore') 

,但是失败了

错误:UnicodeDecodeError:“ascii”编解码器无法解码字节 0xe2

【问题讨论】:

  • 看起来这并不是真正产生错误的代码,因为错误来自尝试将字符串解码为 ascii。 rawtxt 是从哪里来的?
  • @Sarien:它是产生错误的代码。您可以在调用 encode 时收到解码错误。见:chat.stackoverflow.com/rooms/10/conversation/…

标签: python unicode


【解决方案1】:

您遇到了 HTML 实体问题,而不是 unicode 或 UTF-8。试试这个:

import HTMLParser
h = HTMLParser.HTMLParser()
s = h.unescape('If I'm reading lots of articles')
print s

这打印If I'm reading lots of articles

【讨论】:

  • 感谢您节省大量时间
  • @user595169 不客气 :)
猜你喜欢
  • 2018-01-14
  • 1970-01-01
  • 2018-05-17
  • 2014-01-24
  • 2018-02-18
  • 2014-04-23
  • 2013-09-11
  • 2019-09-15
  • 2018-06-17
相关资源
最近更新 更多