[英]TypeError: compile() expected string without null bytes
I am trying to translate a string using google translate API. 我正在尝试使用谷歌翻译API翻译字符串。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import urllib
import urllib2
import ast
url = 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q='+urllib.quote(' '.join(sys.argv[3:])) +'&langpair='+sys.argv[1]+'%7C'+sys.argv[2]
print url
transtext =urllib2.urlopen(urllib2.Request(url)).read()
content=ast.literal_eval(transtext)
print content['responseData']['translatedText']
python testURL.py hi en 'नमस्ते' python testURL.py你好'नमस्ते'
this is the url given . 这是给出的网址。
http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%E0%A4%A8%E0%A4%AE%E0%A4%B8%E0%A5%8D%E0%A4%A4%E0%A5%87&langpair=hi%7Cen If we check the above url we can see the Output is Hello http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%E0%A4%A8%E0%A4%AE%E0%A4%B8%E0%A5%8D%E0% A4%A4%E0%A5%87&langpair = hi%7Cen如果我们检查上面的url我们可以看到输出是你好
{"responseData": {"translatedText":"Hello"}, "responseDetails": null, "responseStatus": 200}
this is in string format so im trying to convert it to dictionary format using ast.literal_eval and then acess the data in dictionary by content['responseData']['translatedText'] but following error occurs 这是字符串格式,所以我试图使用ast.literal_eval将其转换为字典格式,然后通过内容['responseData'] ['translatedText']访问字典中的数据但发生以下错误
Error: 错误:
content=ast.literal_eval(transtext)
File "/usr/lib/python2.6/ast.py", line 49, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/usr/lib/python2.6/ast.py", line 37, in parse
return compile(expr, filename, mode, PyCF_ONLY_AST)
TypeError: compile() expected string without null bytes
python version 2.6 and OS Ubuntu 9.10 python版本2.6和操作系统Ubuntu 9.10
The response you get are likely in JSON format. 您获得的响应可能是JSON格式。 Try using the json module, which is included with Python 2.6.
尝试使用Python 2.6附带的json模块。
literal_eval expects Python representations, which don't include null. literal_eval需要Python表示,不包括null。 It's JSON, so use
json.loads(transtext)
它是JSON,所以使用
json.loads(transtext)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.