为了对URI进行编码,我使用了urllib.quote("schönefeld"),但是当字符串中存在一些非ascii字符时,它将使用thorws。
KeyError: u'\xe9'
Code: return ''.join(map(quoter, s))我的输入字符串是köln, brønshøj, schönefeld等。
当我尝试只在windows中打印语句时(使用python2.7,pyscripter )。但在linux中,它会引发异常(我猜平台并不重要)。
这就是我想要做的:
from commands import getstatusoutput
queryParams = "schönefeld";
cmdString = "http://baseurl" + quote(queryParams)
print getstatusoutput(cmdString)探究了问题的原因: in urllib.quote(),实际上是在return ''.join(map(quoter, s))抛出异常。
urllib中的代码是:
def quote(s, safe='/'):
if not s:
if s is None:
raise TypeError('None object cannot be quoted')
return s
cachekey = (safe, always_safe)
try:
(quoter, safe) = _safe_quoters[cachekey]
except KeyError:
safe_map = _safe_map.copy()
safe_map.update([(c, c) for c in safe])
quoter = safe_map.__getitem__
safe = always_safe + safe
_safe_quoters[cachekey] = (quoter, safe)
if not s.rstrip(safe):
return s
return ''.join(map(quoter, s))异常的原因是在''.join(map(quoter, s))中,对于s中的每个元素,都将调用商函数,最后列表将由'‘加入并返回。
对于非ascii char è,等价的键将是%E8,它以_safe_map变量表示.但是,当我调用引号(‘è“)时,它会搜索键\xe8。使密钥不存在并引发异常。
因此,我只是修改了s = [el.upper().replace("\\X","%") for el in s],然后在try-除块中调用''.join(map(quoter, s))。现在它很好用。
但我很烦人,我所做的是正确的做法,否则会造成任何其他问题?而且,我也有linux的200+实例,它很难在所有实例中部署这个修复程序。
发布于 2013-02-27 15:19:23
您正在尝试引用Unicode数据,因此您需要决定如何将其转换为URL安全字节。
首先将字符串编码为字节。经常使用UTF-8:
>>> import urllib
>>> urllib.quote(u'sch\xe9nefeld')
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py:1268: 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 "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 1268, in quote
return ''.join(map(quoter, s))
KeyError: u'\xe9'
>>> urllib.quote(u'sch\xe9nefeld'.encode('utf8'))
'sch%C3%A9nefeld'但是,编码取决于服务器将接受什么。最好坚持原表单被发送的编码。
发布于 2013-12-17 11:42:26
通过将字符串转换为unicode,我解决了这个问题。
下面是片段:
try:
unicode(mystring, "ascii")
except UnicodeError:
mystring = unicode(mystring, "utf-8")
else:
pass解决方案的详细说明可在http://effbot.org/pyfaq/what-does-unicodeerror-ascii-decoding-encoding-error-ordinal-not-in-range-128-mean.htm上找到
发布于 2015-07-28 14:51:35
我的错误与@ _safe_map完全相同,但在我的例子中,问题在于映射(商,s)试图查找不在_safe_map中的键_safe_map。但是\xe9是,所以我解决了这个问题,用\xe9代替了s中的\xe9。
而且,return语句不应该在try/except中吗?我也不得不改变这一点来彻底解决问题。
https://stackoverflow.com/questions/15115588
复制相似问题