Language Translation in PYTHON
googletrans :
googletrans is a free and unlimited Python library that implemented Google Translate API.
Installation :
pip install googletrans
Starter code (with explanation) :
1. from googletrans import Translator
2. trans = Translator()
3. t = trans.translate("Bom Dia", src = "pt", dest = "en")
4. print(f"Source : {t.src}")
5. print(Destination : {t.dest}")
6. print(" {t.origin} --> {t.text}")
Explanation :
1. Importing "Translator" function from googletrans library.
2. Making a "trans" object for "Translator()" class.
3. ".translate" is the function used for translating a given string to destination language. "Bom Dia" is the string to be translated, in "src" attribute source language's code (i.e. the language of given string) and in "dest" attribute, destination language code is given.
4. "t.src" returns source language.
5. "t.dest" returns destination language.
6. "t.origin" for original text and "t.text" for translated text.
To print codes of all the available languages :
1. from googletrans import LANGUAGES
2. for lang in LANGUAGES:
3. print(f" {lang} --> {LANGUAGES [lang]}")
Explanation :
1. importing LANGUAGES function from googletrans library (LANGUAGES contains all the supported languages with their codes eg. "en" for English, as dictionary).
2. for loop to print all languages in a proper order.
Basic language Translation program :
from googletrans import Translator, LANGUAGES
t= Translator()
def main():
global t
run = True
while run:
que = input("translate(t) or list_of_codes(l) or exit: ").lower()
if que == "l":
for lang in LANGUAGES:
print(f"{lang} --> {LANGUAGES [lang]}")
elif que == "t":
orig = input("original language code : ").lower()
tbt = input("::: ")
des = input("destination language code : ").lower()
tb = t.translate(tbt, src = orig, dest = des)
print(f"translation : {tb.text}")
elif que == "exit":
run = False
if __name__ == "__main__":
main()
@projectsofcode on Instagram
Comments
Post a Comment