TypeError: compile() expected string without null bytes
I am trying to translate a string using google translate 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 'नमस्ते'
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
{"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
Error:
content=ast.literal_eval(transtext)
File "/usr/lib/python2.6/ast.py", line 49, in lit开发者_运维技巧eral_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
The response you get are likely in JSON format. Try using the json module, which is included with Python 2.6.
literal_eval expects Python representations, which don't include null. It's JSON, so use json.loads(transtext)
精彩评论