Rom*_*man 2 python unicode encoding utf-8
我有一个Python代码,试图读取用西里尔字母(例如俄语)编写的RSS源.这是我使用的代码:
import feedparser
from urllib2 import Request, urlopen
d=feedparser.parse(source_url)
# Make a loop over the entries of the RSS feed.
for e in d.entries:
# Get the title of the news.
title = e.title
title = title.replace(' ','%20')
title = title.encode('utf-8')
# Get the URL of the entry.
url = e.link
url = url.encode('utf-8')
# Make the request.
address = 'http://example.org/save_link.php?title=' + title + '&source=' + source_name + '&url=' + url
# Submit the link.
req = Request(address)
f = urlopen(req)
Run Code Online (Sandbox Code Playgroud)
我使用,encode('utf-8')因为标题是用西里尔字母给出的,它工作正常.RSS源的一个例子就在这里.当我尝试从另一个URL读取RSS源列表时出现问题.更详细地说,有一个网页,其中包含RSS源列表(源的URL以及用西里尔字母给出的名称).列表的一个示例如下:
<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>
<html>
<head>
<title></title>
<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>
ua, ?????????????, http://k.img.com.ua/rss/ua/news.xml
ua, ?????????? ??????, http://www.pravda.com.ua/rss/
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
当我尝试将encode('utf-8')应用于本文档中给出的西里尔字母时,会出现问题.我得到了UnicodeDecodeError.有人知道为什么吗?
encode只有UnicodeDecodeError当你提供一个str然后尝试解码的对象时才会给出unicode; 请参阅http://wiki.python.org/moin/UnicodeDecodeError.
您需要首先解码str对象unicode:
name = name.decode('utf-8')
Run Code Online (Sandbox Code Playgroud)
这将采用strUTF-8编码并为您提供一个unicode对象.
它适用于您发布的代码,因为它feedparser返回已解码的Feed数据unicode.
| 归档时间: |
|
| 查看次数: |
193 次 |
| 最近记录: |