2013-04-30 86 views
2

我想找出一种方法来处理在标准Ascii图表中找不到的特殊字符。我正在做一些翻译诗歌来熟悉httplib和urllib模块。问题在于,当用不同的字母表翻译到另一个字母时,意味着一些从英语到西班牙语/法语到英语的短语工作,但前提是我明智地选择我的话语以避免任何冲突(破坏目的)。请原谅我通过的奇怪句子,我并不完全有迷人的话。Python翻译诗歌Ascii麻烦

import httplib, urllib, json 
connObj = httplib.HTTPConnection("api.mymemory.translated.net") 
def simpleTrans(conn, text, ln1, ln2): 
    paramDict = {'q': text, 
       'langpair':ln1+"|"+ln2} 
    params = urllib.urlencode(paramDict) 
    conn.request("GET","/get?"+params) 
    res = connObj.getresponse() 
    serializedText = res.read() 
    responseDict = json.loads(serializedText) 
    return responseDict['responseData']['translatedText'] 


a = simpleTrans(connObj, "man eats dogs for the sake of poetry police give him ten years in jail", 'en', 'fr') 
b = simpleTrans(connObj, a, 'fr', 'es') 
c = simpleTrans(connObj, b, 'es', 'no') 
print (simpleTrans(connObj, c, 'no', 'en')) 

这会产生如预期的下列错误。

bash-3.2$ python translationPoetry.py 
Traceback (most recent call last): 
    File "translationPoetry.py", line 15, in <module> 
    b = simpleTrans(connObj, a, 'fr', 'es') 
    File "translationPoetry.py", line 6, in simpleTrans 
    params = urllib.urlencode(paramDict) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 1294, in urlencode 
**UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 54: ordinal not in range(128)** 

如果有人可以为我反弹一些想法,我会非常感激!

+0

变化'返回responseDict [ 'responseData'] [ 'translatedText']'到'返回responseDict [ 'responseData'] [ 'translatedText']。编码( 'UTF-8')'和看看是否有帮助。 – Blender 2013-04-30 02:54:20

+0

工作就像一个魅力,要做更​​多的研究。非常感谢。 – 2013-04-30 03:06:23

回答

0

ASCII是一个有限的字符集,因为所有字符都需要用8位表示。我建议你看看Unicode。 Unicode是一种标准格式,它不仅可以表示英语词汇。

您可以开始here

也看看函数decode()。

st = 'ASCII character string.' 
st.decode('utf-8') 
+0

感谢您的链接!像魅力一样工作。 – 2013-05-03 00:34:34