2012-11-02 194 views
0

我正在使用Microsoft的免费翻译服务将一些印地语字符翻译为英语。他们不提供一个Python API,但我借来代码:tinyurl.com/dxh6thr如何将Unicode字符串作为参数传递给urllib.urlencode()

我想这里的描述使用“检测”的方法:tinyurl.com/bxkt3we

的'hindi.txt'文件保存在unicode字符集中。

>>> hindi_string = open('hindi.txt').read() 
>>> data = { 'text' : hindi_string } 
>>> token = msmt.get_access_token(MY_USERID, MY_TOKEN) 
>>> request = urllib2.Request('http://api.microsofttranslator.com/v2/Http.svc/Detect?'+urllib.urlencode(data)) 
>>> request.add_header('Authorization', 'Bearer '+token) 
>>> response = urllib2.urlopen(request) 
>>> print response.read() 
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">en</string> 
>>> 

响应显示翻译器检测到'en',而不是'hi'(用于印地语)。当我检查的编码,它显示为“字符串”:

>>> type(hindi_string) 
<type 'str'> 

供参考,在这里是“hindi.txt”的内容:

हाय, कैसे आप आज कर रहे हैं। मैं अच्छी तरह से, आपको धन्यवाद कर रहा हूँ। 

我不知道,如果使用string.encode或string.decode在这里适用。如果是这样,我需要对/从/进行编码/解码需要什么?将一个Unicode字符串作为urllib.urlencode参数传递的最佳方法是什么?我如何确保实际的印地语字符作为参数传递?

谢谢。

的建议,但我得到以下错误**附加信息**

我尝试使用codecs.open():

>>> hindi_new = codecs.open('hindi.txt', encoding='utf-8').read() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "C:\Python27\lib\codecs.py", line 671, in read 
    return self.reader.read(size) 
    File "C:\Python27\lib\codecs.py", line 477, in read 
    newchars, decodedbytes = self.decode(data, self.errors) 
UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte 

这里是再版(hindi_string)输出:

>>> repr(hindi_string) 
"'\\xff\\xfe9\\t>\\t/\\t,\\x00 \\x00\\x15\\tH\\t8\\tG\\t \\x00\\x06\\t*\\t \\x00 
\\x06\\t\\x1c\\t \\x00\\x15\\t0\\t \\x000\\t9\\tG\\t \\x009\\tH\\t\\x02\\td\\t \ 
\x00.\\tH\\t\\x02\\t \\x00\\x05\\t'" 
+0

在其编码你保存文件?您是否尝试使用'codecs.open'而不是简单的'open'来获取正确编码的文件内容? – Bakuriu

+0

您显示'hindi_string'定义但不是'hindi'。请显示'repr(印地语)'。 – eryksun

+0

阅读[绝对最小每个软件开发人员绝对,积极必须知道Unicode和字符集(没有借口!)](http://www.joelonsoftware.com/articles/Unicode.html)。 – katrielalex

回答

2

你的文件是utf-16,所以你需要在发送前对内容进行解码:

hindi_string = open('hindi.txt').read().decode('utf-16') 
data = { 'text' : hindi_string.encode('utf-8') } 
... 
+0

非常感谢您的先生!这工作完美:) –

0

你可以尝试使用codecs.open打开该文件,并将其与utf-8解码:

import codecs 

with codecs.open('hindi.txt', encoding='utf-8') as f: 
    hindi_text = f.read() 
相关问题