Implementation method of translation function translate module in python

  • 2021-08-28 20:42:16
  • OfStack

Nowadays, countries communicate closely, and we break down language barriers through translation, and translation is particularly common on the Internet. In python, the package that performs translation operation is translate package. By downloading and installing translate package, translate module can be used to realize direct mutual translation of multiple languages in python.

1. Download the translate package

https://pypi.org/project/translate/

2. Install the translate package using pip


pip install translate

3. Use translate module to realize translation function


from translate import Translator
def translate_content_ch():
  #  Realize English to Chinese 
  translator=Translator(to_lang='chinese')
  translation=translator.translate('hello')
  return translation
def translate_content_en():
# Realize the conversion from Chinese to English 
  translator=Translator(from_lang='chinese',to_lang='english')
  translation=translator.translate(' How do you do ')
  return translation
Supplementary example of Python translate () method

First, replace the new string according to the transformation table, and then replace the del parameters, in a sequence:


# -*- coding:utf-8 -*-
from string import maketrans

intab = 'aeiou'
outtab = '12345'
str1 = 'i am a example string for test! wow...!!!'

print "str1:",str1
print "intab:",intab
print "outtab:",outtab

transtab = maketrans(intab,outtab)

print "str1.translate(translate(intab,outtab)):"
print str1.translate(transtab)

print "str1.translate(translate(intab,outtab),'x1'):"
print str1.translate(transtab,'x1')

The output is:


str1: i am a example string for test! wow...!!!
intab: aeiou
outtab: 12345
str1.translate(translate(intab,outtab)):
3 1m 1 2x1mpl2 str3ng f4r t2st! w4w...!!!
str1.translate(translate(intab,outtab),'x1'):
3 1m 1 21mpl2 str3ng f4r t2st! w4w...!!!

Related articles: