有没有办法告诉Python - 我认为这是最新和现代的语言,只使用Unicode字符串,而不让我使用`.encode('utf-8')`之类的东西?
我知道... Python 3.0应该可以做到这一点,但我不能使用3.0,而且2.7并不算太老...
例如:
url = "http://en.wikipedia.org//w/api.php?action=query&list=search&format=json&srlimit=" + str(items) + "&srsearch=" + urllib2.quote(title.encode('utf-8'))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 19: ordinal not in range(128)
更新
如果我从所有代码中删除所有的.encode
语句,并在#!/usr/bin/python
的下面添加# -*- coding: utf-8 -*-
,那么我得到的结果与如果我根本没有添加# -*- coding: utf-8 -*-
一样。
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py:1250: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
return ''.join(map(quoter, s))
Traceback (most recent call last):
File "classes.py", line 583, in <module>
wiki.getPage(title)
File "classes.py", line 146, in getPage
url = "http://en.wikipedia.org/w/api.php?action=query&prop=revisions&format=json&rvprop=content&rvlimit=1&titles=" + urllib2.quote(title)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 1250, in quote
return ''.join(map(quoter, s))
KeyError: u'\xf1'
我并不手动输入任何字符串,而是从网站解析HTML和JSON。因此,这些脚本/字节流/无论它们是什么,都是由Python创建的。
更新2:我可以将错误移动到其他地方,但它只是在新的位置上不断出现。我原本希望Python能成为一个有用的脚本工具,但看起来三天没有运气,我将尝试使用另一种语言。很遗憾,Python已预安装在OSX上。我已标记正确的答案,以解决我发布的一个错误实例。