Skip to content

Commit 0ae66ac

Browse files
committed
added translating text tutorial
1 parent 7974567 commit 0ae66ac

File tree

8 files changed

+161
-0
lines changed

8 files changed

+161
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -98,5 +98,6 @@ This is a repository of all the tutorials of [The Python Code](https://www.thepy
9898
- [How to Use Google Custom Search Engine API in Python](https://www.thepythoncode.com/article/use-google-custom-search-engine-api-in-python). ([code](general/using-custom-search-engine-api))
9999
- [How to Use Github API in Python](https://www.thepythoncode.com/article/using-github-api-in-python). ([code](general/github-api))
100100
- [How to Use Google Drive API in Python](https://www.thepythoncode.com/article/using-google-drive--api-in-python). ([code](general/using-google-drive-api))
101+
- [How to Translate Text in Python](https://www.thepythoncode.com/article/translate-text-in-python). ([code](general/using-google-translate-api))
101102

102103
For any feedback, please consider pulling requests.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# [How to Translate Text in Python](https://www.thepythoncode.com/article/translate-text-in-python)
2+
To run this:
3+
- `pip3 install -r requirements.txt`
4+
- Tutorial code is in `translator.py`.
5+
- If you want to translate a document, you can use `translate_doc.py`:
6+
```
7+
python3 translate_doc.py --help
8+
```
9+
**Output:**
10+
```
11+
usage: translate_doc.py [-h] [-s SOURCE] [-d DESTINATION] target
12+
13+
Simple Python script to translate text using Google Translate API (googletrans
14+
wrapper)
15+
16+
positional arguments:
17+
target Text/Document to translate
18+
19+
optional arguments:
20+
-h, --help show this help message and exit
21+
-s SOURCE, --source SOURCE
22+
Source language, default is Google Translate's auto
23+
detection
24+
-d DESTINATION, --destination DESTINATION
25+
Destination language, default is English
26+
```
27+
- For instance, if you want to translate text in the document `wonderland.txt` from english (`en` as language code) to arabic (`ar` as language code):
28+
```
29+
python translate_doc.py wonderland.txt --source en --destination ar
30+
```
31+
A new file `wonderland_ar.txt` will appear in the current directory that contains the translated document.
32+
- You can also translate text and print in the stdout using `translate_doc.py`:
33+
```
34+
python translate_doc.py 'Bonjour' -s fr -d en
35+
```
36+
**Output:**
37+
```
38+
'Hello'
39+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
googletrans
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from googletrans import Translator
2+
import argparse
3+
import os
4+
5+
# init the translator
6+
translator = Translator()
7+
8+
def translate(text, src="auto", dest="en"):
9+
"""Translate `text` from `src` language to `dest`"""
10+
return translator.translate(text, src=src, dest=dest).text
11+
12+
13+
if __name__ == "__main__":
14+
parser = argparse.ArgumentParser(description="Simple Python script to translate text using Google Translate API (googletrans wrapper)")
15+
parser.add_argument("target", help="Text/Document to translate")
16+
parser.add_argument("-s", "--source", help="Source language, default is Google Translate's auto detection", default="auto")
17+
parser.add_argument("-d", "--destination", help="Destination language, default is English", default="en")
18+
19+
args = parser.parse_args()
20+
target = args.target
21+
src = args.source
22+
dest = args.destination
23+
24+
if os.path.isfile(target):
25+
# translate a document instead
26+
# get basename of file
27+
basename = os.path.basename(target)
28+
# get the path dir
29+
dirname = os.path.dirname(target)
30+
try:
31+
filename, ext = basename.split(".")
32+
except:
33+
# no extension
34+
filename = basename
35+
ext = ""
36+
37+
translated_text = translate(open(target).read(), src=src, dest=dest)
38+
# write to new document file
39+
open(os.path.join(dirname, f"{filename}_{dest}{f'.{ext}' if ext else ''}"), "w").write(translated_text)
40+
else:
41+
# not a file, just text, print the translated text to standard output
42+
print(translate(target, src=src, dest=dest))
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from googletrans import Translator, constants
2+
from pprint import pprint
3+
4+
# init the Google API translator
5+
translator = Translator()
6+
7+
# translate a spanish text to english text (by default)
8+
translation = translator.translate("Hola Mundo")
9+
print(f"{translation.origin} ({translation.src}) --> {translation.text} ({translation.dest})")
10+
11+
# translate a spanish text to arabic for instance
12+
translation = translator.translate("Hola Mundo", dest="ar")
13+
print(f"{translation.origin} ({translation.src}) --> {translation.text} ({translation.dest})")
14+
15+
# specify source language
16+
translation = translator.translate("Wie gehts ?", src="de")
17+
print(f"{translation.origin} ({translation.src}) --> {translation.text} ({translation.dest})")
18+
# print all translations and other data
19+
pprint(translation.extra_data)
20+
21+
# translate more than a phrase
22+
sentences = [
23+
"Hello everyone",
24+
"How are you ?",
25+
"Do you speak english ?",
26+
"Good bye!"
27+
]
28+
translations = translator.translate(sentences, dest="tr")
29+
for translation in translations:
30+
print(f"{translation.origin} ({translation.src}) --> {translation.text} ({translation.dest})")
31+
32+
# detect a language
33+
detection = translator.detect("नमस्ते दुनिया")
34+
print("Language code:", detection.lang)
35+
print("Confidence:", detection.confidence)
36+
# print the detected language
37+
print("Language:", constants.LANGUAGES[detection.lang])
38+
39+
# print all available languages
40+
print("Total supported languages:", len(constants.LANGUAGES))
41+
print("Languages:")
42+
pprint(constants.LANGUAGES)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+

2+
There was nothing so VERY remarkable in that; nor did Alice think it so
3+
VERY much out of the way to hear the Rabbit say to itself, 'Oh dear!
4+
Oh dear! I shall be late!' (when she thought it over afterwards, it
5+
occurred to her that she ought to have wondered at this, but at the time
6+
it all seemed quite natural); but when the Rabbit actually TOOK A WATCH
7+
OUT OF ITS WAISTCOAT-POCKET, and looked at it, and then hurried on,
8+
Alice started to her feet, for it flashed across her mind that she had
9+
never before seen a rabbit with either a waistcoat-pocket, or a watch
10+
to take out of it, and burning with curiosity, she ran across the field
11+
after it, and fortunately was just in time to see it pop down a large
12+
rabbit-hole under the hedge.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
2+
لم يكن هناك شيء حتى ملحوظا جدا في ذلك. كما لم أليس اعتقد انه حتى
3+
كثيرا للخروج من الطريق لسماع الكلمة الأرنب لنفسها، "يا عزيزي!
4+
يا للهول! سوف أتأخر!' (عندما ظنت أنها فوق بعد ذلك، فإنه
5+
وقعت لها أنها يجب أن تساءل في هذا، ولكن في الوقت
6+
كل شيء يبدو طبيعيا)؛ ولكن عندما الأرنب قد حصلت فعلا وWATCH
7+
OUT OF ITS صدرية-POCKET، ونظر إليها، ثم سارع على،
8+
التي أليس على قدميها، لأنها تومض عبر عقلها أن لديها
9+
لم يشاهد من قبل أرنب إما مع صدرية الجيب، أو ساعة
10+
لإخراج منه، وحرق مع الفضول، ركضت عبر الميدان
11+
بعد ذلك، وكان لحسن الحظ في الوقت المناسب تماما لرؤيتها البوب ​​بانخفاض كبير
12+
أرنب حفرة تحت التحوط.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
2+
O yüzden çok dikkat çekici bir şey yoktu; ne de Alice öyle düşündün
3+
yol ÇOK fazla dışarı ', kendisine Ah canım Tavşan söz duymak!
4+
Ah hayatım! Geç olacaktır!' (O sonradan ters düşünürken, bunu
5+
Ona meydana geldiği o şuna merak gerekirdi, ama zaman
6+
hepsi) çok doğal görünüyordu; ancak Tavşan aslında bir İZLEYİN BAŞLADI zaman
7+
ITS YELEK-cebinden ve, ona baktım ve ardından aceleyle
8+
o o vardı aklında boyunca parladı için Alice ayağa başladı
9+
önce yelek-cebinde ya da bir saatin ya sahip bir tavşan görmedim
10+
bunun dışında almak ve merakla yanan için, o alanın karşılaştım
11+
ondan sonra, ve neyse o büyük aşağı pop görmek için tam zamanında oldu
12+
çit altında tavşan delikli.

0 commit comments

Comments
 (0)