我试图找出一种方法来处理在标准 Ascii 图表中找不到的特殊字符。我正在做一些翻译诗来熟悉 httplib 和 urllib 模块。问题是当用不同的字母从一种语言翻译成另一种语言时,这意味着从英语到西班牙语/法语到英语的一些短语可以工作,但前提是我提前明智地选择了我的单词以避免任何冲突(违背了目的)。请原谅我说的奇怪的句子,我完全没有办法用迷人的词。
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)**
如果有人可以为我提出一些想法,我将非常感激!