|
|
What this is
This file is included in the DevDaily.com
"Ruby Source Code
Warehouse" project. The intent of this project is to help you "Learn
Ruby by Example" TM.
Other links
The source code
#!/usr/bin/env ruby
require 'net/http'
require 'cgi'
module BabelFish
MAGIC_LINE_NUMBER_IN_BABELFISH_WHICH_CONTAINS_TEXTAREA = 65
def BabelFish.random_language
langs = ["fr", "it", "ko", "zh", "ja", "pt", "es"]
return langs[rand(langs.size - 1)]
end
def BabelFish.translate(languages, input)
str = CGI::escape(input)
conn = Net::HTTP.new("babelfish.altavista.com")
resp, data = conn.get("/tr?doit=done&tt=urltext&urltext=#{str}&lp=#{languages}&submit=Translate")
lame_state_variable = false
translation = ""
if(data.split("\n")[MAGIC_LINE_NUMBER_IN_BABELFISH_WHICH_CONTAINS_TEXTAREA] =~ //
ending_match = /^<\/td>/
end
data.each do | line |
if(lame_state_variable) then
if(line =~ ending_match) then
lame_state_variable = false
else
translation << line
end
else
if(line =~ starting_match) then
lame_state_variable = true
translation = line.split(">")[1]
end
end
end
return translation
end
def BabelFish.stupidize(some_text, *lang_args)
# stupidize(text_to_stupidize, source_language, language_to_use_when_stupidizing)
# source_language defaults to English
# language_to_use_when_stupidizing defaults to a random language
lang = lang_args[0]
mangler = lang_args[1]
mangler ||= random_language
lang ||= "en"
trans = translate("#{lang}_#{mangler}", some_text)
return translate("#{mangler}_#{lang}", trans)
end
end
# Here's an example of how to use this library.
# Of course, you can 'require' it into your own programs and use it on any
# text you'd like.
if __FILE__ == $0 then
input = ""
while gets do
input << $_
end
puts BabelFish.stupidize(input, "en") # English source language
# with random intermediary
#puts BabelFish.stupidize(input, "en", "es") #this would also work
end
|