Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Quick English to Portuguese 1-word Translator (See related posts)

// description of your code here
This is a very simple python code that access babylon translator. For now It just translates 1-word from english to portuguese. It's probably a bit buggy also, because I'm a python noob.

import urllib2, sys, re

def translate(word, lang):
	print "WORD: "+word
	print "TRANSLATION TO LANGUAGE: "+lang
	print "-----------------------------------"
	sock = urllib2.urlopen("http://online.babylon.com/cgi-bin/trans.cgi?layout=txt&lang=ptg&word="+word)
	htmlsource = sock.read()
	sock.close()

	#Replacing some specific html tags for \n in order to format the final output:
	htmlsource = htmlsource.replace("<hr>","\n");
	htmlsource = htmlsource.replace("<BR>","\n");
	htmlsource = htmlsource.replace("<br>","\n");
	htmlsource = htmlsource.replace("</BR>","");
	htmlsource = htmlsource.replace("</br>","");
	htmlsource = htmlsource.split(word)[1]

	#Removing unwanted html tags (acctually all the tags):
	iter = re.finditer(r'<.*?>',htmlsource)
	for m in iter:
		htmlsource = htmlsource.replace(m.string[m.start():m.end()],"")

	#More output formating
	tags = htmlsource.split("\n");
	output = ""
	for str in tags:
		output += str.strip()+"\n"

	#tweak this up for your language
	output = output.decode("iso-8859-1").encode("utf-8")	
	print output

try:
	word = sys.argv[1]
	lang = sys.argv[2]
	translate(word,"")

except(IndexError):
	if(word.__len__() != 0):
		translate(word, "")

You need to create an account or log in to post comments to this site.


Click here to browse all 4829 code snippets

Related Posts