py-translate is a CLI Tool for Google Translate written in Python!
Author: | Sang Han 2014 |
---|---|
License: | Apache Software License v2 |
Version: | v1.0.3 |
A Translation Tool for Humans
Translate Lewis Carroll: Alice in Wonderland
The end goal is a simple application for translating text in the terminal. Text can be generated interactively or programmatically in the shell environment. Through command line arguments, file descriptors or pipes generating translated output that can be piped to a file or displayed on the terminal.
$ pip install py-translate
$ git clone https://github.com/jjangsangy/py-translate.git
$ python setup.py install
translate [--flags] [source] dest
¶Positional | |
---|---|
dest | Destination language code |
source | Source language code |
Optional | |
-h,–help | Show this help message and exit |
-v, –version | Show program’s version number and exit |
-l,–list [code] | Enumerate the name of country and language code pair. |
[ Optionally specify output language format ] | |
–translit | Print out the transliteration of the text |
Hello World from English to Traditional Chinese
$ translate en zh-TW <<< 'Hello World!'
你好世界!
Hello World
# Translate Hello from French to English
$ translate fr en <<< 'Bonjour, comment allez-vous!'
Hello, how are you?
Omitting the source language will try to detect it based on the text content
$ translate fr <<< 'I think therefore I am'
Je pense donc je suis
$ translate --translit en ko <<< 'Want to fight!'
ssaugo sip-eo!
$ translate --translit en zh-TW <<< 'Kidding, we should be friends'
Kāiwánxiào, wǒmen yīnggāi shì péngyǒu
$ translate zh-TW < 'alice.txt'
阿麗思道:「你不是說你要告訴你的歷史嗎?告訴我你為甚麼恨—那個—那些—C和D,」
她末了兩個字母輕輕兒地說的,怕回來又得罪了牠。
那老鼠對著阿麗思嘆了一口氣道,「唉﹗我的身世說來可真是又長又苦又委屈呀—」
阿麗思聽了,瞧著那老鼠的尾巴說,「你這尾是曲啊﹗可是為甚麼又叫它苦呢﹗」
她就一頭聽著那老鼠說話,一頭在在心上納悶,所以她聽的那老鼠講的「尾曲」
的歷史是差不多像這個樣了的
....
# Multiple Chaining
$ echo 'What is love?' | translate en zh-TW | translate zh-TW ko | translate ko fr | translate fr en
What is love?
# Grocery List
$ cat << BUY | translate ko
Celery
Milk
Eggs
Bread
Cereal
BUY
셀러리
우유
달걀
빵
시리얼
Here’s a list of Python platforms that are officially supported.
Find the latest documentation http://pythonhosted.org/py-translate/
$ translate zh-TW <<< "Hello World!"
你好世界!
$ translate ko <<< "Goodbye!"
안녕히 가세요!
$ translate zh-TW < "alice.txt"
阿麗思道:「你不是說你要告訴你的歷史嗎?告訴我你為甚麼恨—那個—那些—C和D,」
她末了兩個字母輕輕兒地說的,怕回來又得罪了牠。
那老鼠對著阿麗思嘆了一口氣道,「唉﹗我的身世說來可真是又長又苦又委屈呀—」
阿麗思聽了,瞧著那老鼠的尾巴說,「你這尾是曲啊﹗可是為甚麼又叫它苦呢﹗」
她就一頭聽著那老鼠說話,一頭在在心上納悶,所以她聽的那老鼠講的「尾曲」
的歷史是差不多像這個樣了的
# Redirect any output through a unix pipe.
$ python --help | translate fr
D'autres variables d'environnement
PYTHONSTARTUP: le fichier exécuté au démarrage interactif (pas par défaut)
PYTHONPATH: ':'-liste de répertoires séparés préfixés à la
module par défaut chemin de recherche. Le résultat est sys.path.
PYTHONHOME: Annuaire <prefix> suppléant (ou <prefix> <exec_prefix>).
PYTHONCASEOK: ignorer la casse dans les états d'importation» (Windows).
PYTHONIOENCODING: Codage [: erreurs] utilisés pour stdin / stdout / stderr.
PYTHONHASHSEED: si cette variable est définie à aléatoire, l'effet est le même
comme spécifiant l'option-R: une valeur aléatoire est utilisée pour ensemencer les hashs de
str, octets et objets datetime. Il peut également être défini à un nombre entier
dans l'intervalle [0,4294967295] pour obtenir des valeurs de hachage avec une graine prévisible.
# A "Here-String" Grocery List
$ cat <<- GROCERY_LIST | translate ko
Celery
Milk
Eggs
Bread
Cereal
GROCERY_LIST
셀러리
우유
달걀
빵
시리얼
# Translate Telephone!
$ echo 'What is love?' | translate zh-TW | translate ko | translate fr | translate en
What is love?
Requires at least one command line argument for the destination language. If no command line arguments are passed, an error message will be passed.
$ translate | "Error! No Arguments"
usage: translate [-h] [-v] [-l [code]] [source] dest
translate: error: the following arguments are required: dest
See Usage section for usage information
Use the -l option to see all the possible language codes.
$ translate -l
Specify the output format by language code
$ translate -l zh-TW
Language | Code |
---|---|
Afrikaans | af |
Albanian | sq |
Arabic | ar |
Azerbaijani | az |
Basque | eu |
Belarusian | be |
Bengali | bn |
Bosnian | bs |
Bulgarian | bg |
Catalan | ca |
Cebuano | ceb |
Chinese (Simplified) | zh |
Chinese (Traditional) | zh-TW |
Croatian | hr |
Czech | cs |
Danish | da |
Dutch | nl |
English | en |
Esperanto | eo |
Estonian | et |
Filipino | tl |
Finnish | fi |
French | fr |
Galician | gl |
Georgian | ka |
German | de |
Greek | el |
Gujarati | gu |
Haitian | Creole ht |
Hebrew | iw |
Hindi | hi |
Hmong | hmn |
Hungarian | hu |
Icelandic | is |
Indonesian | id |
Irish | ga |
Italian | it |
Japanese | ja |
Javanese | jw |
Kannada | kn |
Khmer | km |
Korean | ko |
Lao | lo |
Latin | la |
Latvian | lv |
Lithuanian | lt |
Macedonian | mk |
Malay | ms |
Maltese | mt |
Marathi | mr |
Norwegian | no |
Persian | fa |
Polish | pl |
Portuguese | pt |
Romanian | ro |
Russian | ru |
Serbian | sr |
Slovak | sk |
Slovenian | sl |
Spanish | es |
Swahili | sw |
Swedish | sv |
Tamil | ta |
Telugu | te |
Thai | th |
Turkish | tr |
Ukrainian | uk |
Urdu | ur |
Vietnamese | vi |
Welsh | cy |
Yiddish | yi |
Language | Code |
---|---|
土耳其文 | tr |
中文(繁體) | zh-TW |
中文(簡體) | zh |
丹麥文 | da |
巴斯克文 | eu |
日文 | ja |
爪哇語 | jw |
加里西亞文 | gl |
加泰羅尼亞文 | ca |
卡納達文 | kn |
布爾文 | af |
白俄羅斯語 | be |
立陶宛文 | lt |
冰島文 | is |
匈牙利文 | hu |
印尼文 | id |
印度文 | hi |
印度古哈拉地語 | gu |
西班牙文 | es |
克羅埃西亞文 | hr |
希伯來文 | iw |
希臘文 | el |
亞塞拜然文 | az |
孟加拉文 | bn |
拉丁文 | la |
拉脫維亞文 | lv |
法文 | fr |
波西尼亞 | bs |
波斯語 | fa |
波蘭文 | pl |
芬蘭文 | fi |
阿拉伯文 | ar |
阿爾巴尼亞文 | sq |
俄文 | ru |
保加利亞文 | bg |
威爾斯文 | cy |
苗文 | hmn |
英文 | en |
挪威文 | no |
泰文 | th |
泰米爾文 | ta |
泰盧固文 | te |
海地克里奧文 | ht |
烏克蘭文 | uk |
烏爾都語 | ur |
馬耳他文 | mt |
馬來文 | ms |
馬其頓文 | mk |
馬拉地文 | mr |
高棉文 | km |
國際語文 | eo |
宿霧文 | ceb |
捷克文 | cs |
荷蘭文 | nl |
喬治亞文 | ka |
斯瓦希里文 | sw |
斯洛伐克文 | sk |
斯洛維尼亞文 | sl |
菲律賓文 | tl |
越南文 | vi |
塞爾維亞文 | sr |
意第緒語 | yi |
愛沙尼亞文 | et |
愛爾蘭文 | ga |
瑞典文 | sv |
義大利文 | it |
葡萄牙文 | pt |
寮文 | lo |
德文 | de |
韓文 | ko |
羅馬尼亞文 | ro |
$ git clone https://github.com/jjangsangy/py-translate.git
$ python setup.py install
For full installation instructions for OS X, please visit Mac OS X Full Installation
Mac OS X is a great development enviornment for python. However, using the default python installation which comes with the operating system currently (Mavericks 10.9.2), has many issues in terms of interfacing with third party applications.
Before we can get hacking. We will need to do 3 things
By default, Apple does not package OS X with it’s own C Compiler.
The default way would be to download and install XCode. which is free to anyone with an apple account and can be installed through the App Store.
Another option for Lion, Mountain Lion and Mavericks users, Apple now provides an official Command Line Tools for Xcode package that you can install without needing to install Xcode itself!
You can download it from Apple’s developer site (free registration required) and search for “Command Line Tools”.
Once we have installed GCC and/or command line tools installing homebrew is very straightforward.
Open up a terminal window and enter
$ ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"
This will install the homebrew package manager in you /usr/local/
.
Any packages that you will install, including python can be found in this directory.
We also need to make sure that /usr/local/
is in our $PATH
enviornment before the /bin
. In order to do that, run this command.
echo export PATH="/usr/local/bin:$PATH" >> ~/.profile
Now we’re all set to start installing some packages!
First make sure that homebrew is up to date
$ brew update && brew upgrade
Already up-to-date.
Now we are ready to install python.
$ brew install python
Note
This will install python 2, not python 3.
To install the latest version of Python 3.
$ brew install python3
This will also include pip your python package manager.
First we need to make sure that everything is up to date.
$ pip install --upgrade setuptools
$ pip install --upgrade distribute
$ pip install --upgrade pip
$ pip install --upgrade wheel
Now we’re all ready, we can install py-translate directly from PyPI
$ pip install py-translate
And we’re done!
py-translate
CLI Tool for Google Translate written in Python!
source
¶Source language code
dest
¶Destination language code
If only 1 positional argument is specified, it will be assumed to be dest and source will default to english
Code author: Sang Han <jjangsangy@gmail.com>
translate.
translator
(source, target, phrase, version='0.0 test', charset='utf-8')[source]¶Returns the url encoded string that will be pushed to the translation server for parsing.
List of acceptable language codes for source and target languages can be found as a JSON file in the etc directory.
Some source languages are limited in scope of the possible target languages that are available.
>>> from translate import translator
>>> translator('en', 'zh-TW', 'Hello World!')
'你好世界!'
Parameters: |
|
---|---|
Returns: | Request Interface |
Return type: | Dictionary |
translate.
coroutine
(func)[source]¶Initializes coroutine essentially priming it to the yield statement. Used as a decorator over functions that generate coroutines.
# Basic coroutine producer/consumer pattern
from translate import coroutine
@coroutine
def coroutine_foo(bar):
try:
while True:
baz = (yield)
bar.send(baz)
except GeneratorExit:
bar.close()
Parameters: | func (Function) – Unprimed Generator |
---|---|
Returns: | Initialized Coroutine |
Return type: | Function |
translate.
push_url
(interface)[source]¶Decorates a function returning the url of translation API. Creates and maintains HTTP connection state
Returns a dict response object from the server containing the translated text and metadata of the request body
Parameters: | interface (Function) – Callable Request Interface |
---|
translate.
source
(target, inputstream=<_io.TextIOWrapper name='<stdin>' mode='r' encoding='ANSI_X3.4-1968'>)[source]¶Coroutine starting point. Produces text stream and forwards to consumers
Parameters: |
|
---|
translate.
spool
(iterable, maxlen=1250)[source]¶Consumes text streams and spools them together for more io efficient processes.
Parameters: |
|
---|
translate.
set_task
(translator, translit=False)[source]¶Task Setter Coroutine
End point destination coroutine of a purely consumer type. Delegates Text IO to the write_stream function.
Parameters: |
|
---|
translate.
write_stream
(script, output='trans')[source]¶Parameters: |
|
---|
translate.
accumulator
(init, update)[source]¶Generic accumulator function.
# Simplest Form
>>> a = 'this' + ' '
>>> b = 'that'
>>> c = functools.reduce(accumulator, a, b)
>>> c
'this that'
# The type of the initial value determines output type.
>>> a = 5
>>> b = Hello
>>> c = functools.reduce(accumulator, a, b)
>>> c
10
Parameters: |
|
---|---|
Returns: | Combined Values |
translate.
set_task
(translator, translit=False)[source]Task Setter Coroutine
End point destination coroutine of a purely consumer type. Delegates Text IO to the write_stream function.
Parameters: |
|
---|
translate.
write_stream
(script, output='trans')[source]Parameters: |
|
---|
translate.
translation_table
(language, filepath='supported_translations.json')[source]¶Opens up file located under the etc directory containing language codes and prints them out.
Parameters: | file (str) – Path to location of json file |
---|---|
Returns: | language codes |
Return type: | dict |
Bug Fixes
|
|