【问题标题】:How to solve UnicodeEncodeError while working with Cyrillic (Russian) letters?处理西里尔文(俄文)字母时如何解决 UnicodeEncodeError?
【发布时间】:2012-06-14 07:13:42
【问题描述】:

我尝试使用提要解析器读取 RSS 提要。

import feedparser
url = 'http://example.com/news.xml'
d=feedparser.parse(url)
f = open('rss.dat','w')
for e in d.entries:
   title = e.title
   print >>f, address
f.close()

它适用于英文 RSS 提要,但如果我尝试显示以西里尔字母书写的标题,则会收到 UnicodeEncodeError。它发生在我:

  1. 尝试将标题写入文件。
  2. 尝试在屏幕上显示标题。
  3. 尝试在 URL 中使用它来访问网页。

我的问题是如何轻松解决这个问题。我很想有一个像这样简单的解决方案:

new_title = some_function(title)

有没有办法用 HTML 代码替换每个西里尔字母?

【问题讨论】:

    标签: python unicode encode non-unicode


    【解决方案1】:

    FeedParser 本身可以很好地处理编码,除非它被错误地声明。有关可能的解释,请参阅http://code.google.com/p/feedparser/issues/detail?id=114。似乎 Python 2.5 使用 ascii 作为默认编码,并导致问题。 您能否粘贴实际的提要 URL,以查看那里的编码是如何声明的。如果声明编码看起来是错误的 - 您必须找到一种方法来指示 FeedParser 覆盖默认值。

    编辑:好的,看来错误在打印语句中。 使用

    f.write(title.encode('utf-8'))
    

    【讨论】:

      猜你喜欢
      • 2014-07-16
      • 1970-01-01
      • 1970-01-01
      • 2013-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多