我正试图找出一种方法来处理标准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)**
如果有人能为我反弹一些想法,我将非常感激!
答案 0 :(得分:0)
ASCII是一个有限的字符集,因为所有字符都需要用8位表示。我建议你看一下Unicode。 Unicode是一种标准格式,它不仅能够表示英语词汇。
您可以启动here。
还可以查看函数decode()。
st = 'ASCII character string.'
st.decode('utf-8')