我正在尝试使用 Google Translate API 将卡纳达语(因此编码为 utf-16)文本翻译为英语。插入我的 google api key 后,手动输入我的 URL,https://www.googleapis.com/language/translate/v2?key=key#&q =ಚಿಂಚೋಳಿ&source=kn&target=en,我能够得到我想要的翻译。
问题是,这个 url 是 utf16 编码的。当我尝试使用 urllib 打开 url 时,我收到下面的错误消息。任何有关如何继续或其他继续方式的建议将不胜感激。
编辑: 我相信这个问题可以通过调用 urllib.parse.quote_plus(text) 来解决,其中 text 是 utf16 文本,并用该函数的返回值替换 utf16 文本。
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
urllib.request.urlopen(url)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 156, in urlopen
return opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 469, in open
response = self._open(req, data)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 487, in _open
'_open', req)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 447, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 1283, in https_open
context=self._context, check_hostname=self._check_hostname)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 1248, in do_open
h.request(req.get_method(), req.selector, req.data, headers)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/http/client.py", line 1061, in request
self._send_request(method, url, body, headers)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/http/client.py", line 1089, in _send_request
self.putrequest(method, url, **skips)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/http/client.py", line 953, in putrequest
self._output(request.encode('ascii'))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 73-79: ordinal not in range(128)
最佳答案
The problem is, however, that this url is utf16 encoded
UTF-16 的含义并不像您想象的那样。它是某些系统(例如 Win32 API)的字符串类型内部使用的 Unicode 字符到字节的编码。 UTF-16 几乎从未在网络上使用,因为它与 ASCII 不兼容。
https://www.googleapis.com/language/translate/v2?key=key#&q=ಚಿಂಚೋಳಿ&source=kn&target=en
这不是 URI - URI 只能包含 ASCII 字符。这是一个IRI ,其中可以包含其他 Unicode 字符。
但是 urllib
不支持 IRI。有一些 Python 库直接支持 IRI;或者,您可以将任何 IRI 转换为 urllib
满意的相应 URI。这是通过使用 IDNA 算法对主机名中的任何非 ASCII 字符进行编码,并使用字符的 UTF-8 表示形式上的 URL 编码对地址其他部分(包括查询参数)中的任何非 ASCII 字符进行编码来完成的。 。这给了你这个:
https://www.googleapis.com/language/translate/v2?key=key#&q=%E0%B2%9A%E0%B2%BF%E0%B2%82%E0%B2%9A%E0%B3%8B%E0%B2%B3%E0%B2%BF&source=kn&target=en
但是,这里使用 #
看起来不太正确 - 这是一种从浏览器传入数据的客户端机制,不适用于服务器请求。
通常你会这样做:
baseurl= 'https://www.googleapis.com/language/translate/v2'
text= u'ಚಿಂಚೋಳಿ'
url= baseurl+'?'+urllib.urlencode(dict(
source= 'kn', target= 'en',
q= text.encode('utf-8'),
key= key
))
关于python - 在Python中使用urllib打开UTF16 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16624424/