Created
September 2, 2010 00:36
-
-
Save snim2/561630 to your computer and use it in GitHub Desktop.
Translate text on the command-line using Google translate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| """ | |
| Use Google to translate text in one language to another. | |
| Original code from here: | |
| http://thebigbrowser.blogspot.com/2010/08/use-google-translate-from-console.html | |
| by coldpizza | |
| Sarah Mount, September 2010. | |
| http://snim2.org | |
| """ | |
| from urllib2 import urlopen | |
| from urllib import urlencode | |
| import json | |
| import optparse | |
| import os | |
| import sys | |
| BASE_URL = 'http://ajax.googleapis.com/ajax/services/language/translate?' | |
| def win_console(): | |
| """Hack to be able to display UTF-8 in Windows console | |
| set utf8 console. | |
| """ | |
| os.system('chcp 65001 > nul') | |
| class UniStream(object): | |
| __slots__= 'fileno', 'softspace', | |
| def __init__(self, fileobject): | |
| self.fileno = fileobject.fileno() | |
| self.softspace = False | |
| def write(self, text): | |
| if isinstance(text, unicode): | |
| os.write(self.fileno, text.encode('utf_8')) | |
| else: | |
| os.write(self.fileno, text) | |
| sys.stdout= UniStream(sys.stdout) | |
| sys.stderr= UniStream(sys.stderr) | |
| return | |
| def translate(langpair, text): | |
| """Translate `text` from language `langpair[0]` to language | |
| `langpair[1]` and return the result.. | |
| """ | |
| params = urlencode( (('v', 1.0), | |
| ('q', text), | |
| ('langpair', langpair),) ) | |
| url = BASE_URL + params | |
| response = json.loads(urlopen(url).read()) | |
| translation = response['responseData']['translatedText'] | |
| return translation | |
| def main(): | |
| """Deal with command line arguments and print translation. | |
| """ | |
| # Fix windows console, if necessary. | |
| if sys.platform == 'win32': | |
| win_console() | |
| # Deal with command-line arguments. | |
| usage = """usage: python {0} [options] -s source_language -d dest_language -t text | |
| Available language codes are listed here: | |
| http://code.google.com/apis/ajaxlanguage/documentation/reference.html#LangNameArray | |
| """.format(os.path.basename(sys.argv[0])) | |
| parser = optparse.OptionParser(usage) | |
| parser.add_option('-s', '--source', | |
| action = 'store', | |
| type = 'string', | |
| dest = 'lang1', | |
| help = 'Source language of your text.') | |
| parser.add_option('-d', '--dest', | |
| action = 'store', | |
| type = 'string', | |
| dest = 'lang2', | |
| help = 'Language to translate your text to.') | |
| parser.add_option('-t', '--text', | |
| action = 'store', | |
| type = 'string', | |
| dest = 'text', | |
| help = 'The text you want to translate.') | |
| (options, args) = parser.parse_args() | |
| # If the user does not place quotes around the text they want to | |
| # be translated, options.text needs to be expanded. | |
| if len(args) > 0 and (options.lang1 is not None and options.lang2 is not None): | |
| options.text = ' '.join([options.text] + args) | |
| elif len(args) > 0: | |
| print(parser.usage) | |
| sys.exit(1) | |
| # Perform the translation and print. | |
| langpair = '{0}|{1}'.format(options.lang1, options.lang2) | |
| print(translate(langpair, options.text) + '\n') | |
| return | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://translate.how/ using similar code;
`from googletrans import Translator
translator = Translator()
text = input("Enter text to translate: ")
destination = input("Enter destination language (e.g. fr for French): ")
result = translator.translate(text, dest=destination)
print(f"Original text: {result.origin}")
print(f"Translated text: {result.text}")
`