6

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 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

1
  • 2
    You're not new to this site. Format your code. Commented Dec 9, 2010 at 11:55

2 Answers 2

3

The response you get are likely in JSON format. Try using the json module, which is included with Python 2.6.

Sign up to request clarification or add additional context in comments.

Comments

3

literal_eval expects Python representations, which don't include null. It's JSON, so use json.loads(transtext)

3 Comments

ive tried with json But the following error occurs content=json.loads(transtext) File "/usr/lib/python2.6/json/__init__.py", line 307, in loads return _default_decoder.decode(s) File "/usr/lib/python2.6/json/decoder.py", line 319, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python2.6/json/decoder.py", line 338, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded
@indu: Well, I've just copied and pasted your code, replaced ast.literal_eval with json.loads, and copied your command, and it worked immediately.
ok.its not working.may be its a problem with proxy.i will check.Thanks for the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.