from googletrans import Translator
translator = Translator(service_urls=['translate.google.cn'])
def translate(text, dest='en', src='auto'):
"""
:param text: origin text -> str or list
:param src: origin language -> str
:param dest: translation language -> str
:return: translated text -> str or list
languages: {‘zh-cn’: ‘chinese (simplified)’, ‘zh-tw’: ‘chinese (traditional)’, ‘en’: ‘english’,
‘fr’: ‘french’, ‘it’: ‘italian’, ‘ja’: ‘japanese’, ...}
you can use following statement to supported languages:
import googletrans
print(googletrans.LANGUAGES)
"""
if isinstance(text, str):
return translator.translate(text, dest, src).text
elif isinstance(text, list):
return [translation.text for translation in translator.translate(text, dest, src)]
else:
return None
if __name__ == '__main__':
print(translate("今天的不开心就止于此吧"))
print(translate(["今天的不开心就止于此吧", "明天依旧光芒万丈"]))
print(translate("宝贝", 'zh-tw'))
print(translate("寶貝", src='zh-tw'))
print(translate(["今天的不开心就止于此吧", "明天依旧光芒万丈", "宝贝"], 'zh-tw', 'zh-cn'))