hkbruvold
June 23rd, 2009, 05:27 PM
I made a simple python-program to translate text from English to Japanese and back again. When you translate text from a language to Japanese and back you'll get a funny sentence.
Here is an example:
text: hello, what the hell are you doing today
number: 5
Hi, I was doing
Here it is translating the text to Japanese and back to English 5 times.
Here is the code:
#! /usr/bin/python
from urllib2 import urlopen
from urllib import urlencode
import sys
# The google translate API can be found here:
# http://code.google.com/apis/ajaxlanguage/documentation/#Examples
def translate(source_lang, target_lang, text):
lang1=source_lang
lang2=target_lang
langpair='%s|%s'%(lang1,lang2)
text=''.join(text)
base_url='http://ajax.googleapis.com/ajax/services/language/translate?'
params=urlencode( (('v',1.0),
('q',text),
('langpair',langpair),) )
url=base_url+params
content=urlopen(url).read()
start_idx=content.find('"translatedText":"')+18
translation=content[start_idx:]
end_idx=translation.find('"}, "')
translation=translation[:end_idx]
return translation
text2 = raw_input("text: ")
try:
times = raw_input("number: ")
times = int(times)
except:
print "you need to give me a number!"
for x in range(times):
text1 = translate('en', 'ja', text2)
text2 = translate('ja', 'en', text1)
print text2
This is a modification of a code from the thread:
http://ubuntuforums.org/showthread.php?t=1087457
EDIT: Made the code print each translation.
Here is an example:
text: hello, what the hell are you doing today
number: 5
Hi, I was doing
Here it is translating the text to Japanese and back to English 5 times.
Here is the code:
#! /usr/bin/python
from urllib2 import urlopen
from urllib import urlencode
import sys
# The google translate API can be found here:
# http://code.google.com/apis/ajaxlanguage/documentation/#Examples
def translate(source_lang, target_lang, text):
lang1=source_lang
lang2=target_lang
langpair='%s|%s'%(lang1,lang2)
text=''.join(text)
base_url='http://ajax.googleapis.com/ajax/services/language/translate?'
params=urlencode( (('v',1.0),
('q',text),
('langpair',langpair),) )
url=base_url+params
content=urlopen(url).read()
start_idx=content.find('"translatedText":"')+18
translation=content[start_idx:]
end_idx=translation.find('"}, "')
translation=translation[:end_idx]
return translation
text2 = raw_input("text: ")
try:
times = raw_input("number: ")
times = int(times)
except:
print "you need to give me a number!"
for x in range(times):
text1 = translate('en', 'ja', text2)
text2 = translate('ja', 'en', text1)
print text2
This is a modification of a code from the thread:
http://ubuntuforums.org/showthread.php?t=1087457
EDIT: Made the code print each translation.