本文整理汇总了Python中googletrans.Translator方法的典型用法代码示例。如果您正苦于以下问题:Python googletrans.Translator方法的具体用法?Python googletrans.Translator怎么用?Python googletrans.Translator使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类googletrans
的用法示例。
在下文中一共展示了googletrans.Translator方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import googletrans [as 别名]
# 或者: from googletrans import Translator [as 别名]
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setupUi(self)
self.translator = Translator()
self.destTextEdit.setReadOnly(True)
if GOOGLE_TRANSLATE_AVAILABLE:
self.srcLanguage.addItems(LANGUAGES.keys())
self.srcLanguage.currentTextChanged[str].connect(self.update_src_language)
self.srcLanguage.setCurrentText('English')
else:
self.srcLanguage.hide()
self.translateButton.pressed.connect(self.translate)
self.show()
示例2: translate_doc
# 需要导入模块: import googletrans [as 别名]
# 或者: from googletrans import Translator [as 别名]
def translate_doc(filename, destination='zh-CN', mix=True):
"""
translate a word document type of file and save the result as document and keep the exactly same file format.
:param filename: word doc file
:param destination='zh-CN':
:param mix=True: if True, will have original language and target language into the same doc. paragraphs by paragraphs.
"""
def tx(t): return Translator().translate(t, dest=destination).text
doc = Document(filename)
for p in doc.paragraphs:
txd = tx(p.text)
p.text = p.text + ('\n' + txd if mix else '')
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
txd = tx(cell.text)
p.text = cell.text + ('\n' + txd if mix else '')
f = filename.replace('.doc', destination.lower() + '.doc')
doc.save(f)
示例3: google_translate
# 需要导入模块: import googletrans [as 别名]
# 或者: from googletrans import Translator [as 别名]
def google_translate(link):
translator = Translator() # Google Translate API
pystring = " ".join(link[1:-2])
lang = detect(pystring)
if link[-1] == "english":
id = "en"
elif link[-1] == "spanish":
id = "es"
elif link[-1] == "french":
id = "fr"
elif link[-1] == "german":
id = "de"
elif link[-1] == "italian":
id = "it"
elif link[-1] == "portugese" or link[-1] == "portuguese":
id = "pt"
else:
id = "en"
translated = translator.translate(pystring, src=lang, dest=id) # To Translate the given language to the required language
print(translated.text) # Print the translated script
try:
speak.say("The translated text is "+translated.text)
speak.runAndWait()
except:
print("Error speaking, here is the translated text: {}".format(translated.text))
示例4: __init__
# 需要导入模块: import googletrans [as 别名]
# 或者: from googletrans import Translator [as 别名]
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.setupUi(self)
try:
with open("style.qss") as f:
style = f.read() # 读取样式表
self.setStyleSheet(style)
except:
print("open stylesheet error")
self.originText.setFocus(True)
# Translator
self.trans = QTranslator()
# destination language
self.dest = "zh-CN"
# ui language : 0->zh-CN, 1->en
self.lan = 0
# real-time translate
self.isRealTimeTrans = False
self.isCopyFromTrans = False
self.connectSlots()
示例5: run
# 需要导入模块: import googletrans [as 别名]
# 或者: from googletrans import Translator [as 别名]
def run(self):
Data = []
global GTransData
T = Translator(service_urls=["translate.google.cn"])
# ts = T.translate(['The quick brown fox', 'jumps over', 'the lazy dog'], dest='zh-CN')
try:
ts = T.translate(self.content, dest=self.dest)
if isinstance(ts.text, list):
for i in ts:
Data.append(i.text)
GTransData = Data
else:
GTransData = ts.text
except:
GTransData = "An error happended. Please retry..."
self.trigger.emit() # emit signal once translatation is finfished
示例6: translateInterface
# 需要导入模块: import googletrans [as 别名]
# 或者: from googletrans import Translator [as 别名]
def translateInterface(self, language):
code = self.codes[language]
if code in translations:
config.translationLanguage = language
if hasattr(myTranslation, "translation"):
open("myTranslation.py", "w", encoding="utf-8").close()
return True
else:
print("translating interface into '{0}' ...".format(language))
translator = Translator()
tempDict = {}
for key, value in self.translation.items():
try:
tempDict[key] = translator.translate(value, dest=code).text
except:
tempDict[key] = value
#config.translationLanguage = language
self.writeMyTranslation(tempDict, language)
print("Done")
return True
return False
示例7: createTranslationTemplates
# 需要导入模块: import googletrans [as 别名]
# 或者: from googletrans import Translator [as 别名]
def createTranslationTemplates(self):
if googletransInstall:
for code in self.codes.values():
print("creating '{0}' template ...".format(code))
translator = Translator()
tempDict = {}
for key, value in self.translation.items():
tempDict[key] = value
# Note: Attempted to use Google Translate to translate interface into all languages, but access is blocked in the middle of the operation. It looks like Google blocks access by ip, when there are too many queries within a short time.
# Don't use the following 4 lines, or ip will be blocked for Google Translate
# try:
# tempDict[key] = translator.translate(value, dest=code).text
# except:
# tempDict[key] = value
with open("translations.py", "a", encoding="utf-8") as fileObj:
code = code.replace("-", "")
fileObj.write("uB{0} = {1}\n\n".format(code, pprint.pformat(tempDict)))
示例8: t
# 需要导入模块: import googletrans [as 别名]
# 或者: from googletrans import Translator [as 别名]
def t(dirTagLine, tran):
data = base64.b64decode(tran.replace(';<*', '/')).decode("utf-8")
translator = Translator()
if not data == '':
try:
logging.info("执行翻译")
if dirTagLine == 'censored' or dirTagLine == 'uncensored' or dirTagLine == 'animation':
data = translator.translate(data, src='ja', dest='zh-cn').text
if dirTagLine == 'europe':
data = translator.translate(data, src='en', dest='zh-cn').text
except Exception as ex:
Log('翻译出现异常 :%s' % ex)
translator = None
return data
示例9: send_message
# 需要导入模块: import googletrans [as 别名]
# 或者: from googletrans import Translator [as 别名]
def send_message(chat_id, content):
translator = Translator()
text = translator.translate(content)
url = URL + "sendMessage?chat_id={}&text={}".format(chat_id, text.text)
get_url(url)
示例10: trans_eng
# 需要导入模块: import googletrans [as 别名]
# 或者: from googletrans import Translator [as 别名]
def trans_eng(content_eng):
"""
英文-中文
:param content:
:return:
"""
translator = Translator(service_urls=['translate.google.cn'])
return translator.translate(content_eng, src='en', dest='zh-cn').text
示例11: traduzir
# 需要导入模块: import googletrans [as 别名]
# 或者: from googletrans import Translator [as 别名]
def traduzir(string):
translator = Translator(service_urls=['translate.google.com.br',])
string = translator.translate(string, dest='pt').text
return string
示例12: performTranslation
# 需要导入模块: import googletrans [as 别名]
# 或者: from googletrans import Translator [as 别名]
def performTranslation(srcs, des, tex):
"""
Function to actually perform the translation of text and print the result
"""
translator = Translator()
result = translator.translate(tex, dest=des, src=srcs)
result = u"""
[{src}] {original}
->
[{dest}] {text}
[pron.] {pronunciation}
""".strip().format(src=result.src, dest=result.dest, original=result.origin,
text=result.text, pronunciation=result.pronunciation)
print("\n" + result)
示例13: translation
# 需要导入模块: import googletrans [as 别名]
# 或者: from googletrans import Translator [as 别名]
def translation(article):
translator = Translator()
soup = BeautifulSoup(article, 'lxml')
paragraphs = soup.findAll('p')
for p in paragraphs:
for content in p.contents:
if content.name == None and len(content) > 0:
trans = youdao_translator(content)
#trans = translator.translate(content, src='en', dest='zh-CN').text
#print(len(content), content.name)
#print(content)
#print(trans)
content.replace_with(trans)
return str(soup.body.next)
示例14: translator
# 需要导入模块: import googletrans [as 别名]
# 或者: from googletrans import Translator [as 别名]
def translator():
from googletrans import Translator
return Translator()
示例15: test_bind_multiple_service_urls
# 需要导入模块: import googletrans [as 别名]
# 或者: from googletrans import Translator [as 别名]
def test_bind_multiple_service_urls():
service_urls = [
'translate.google.com',
'translate.google.co.kr',
]
translator = Translator(service_urls=service_urls)
assert translator.service_urls == service_urls
assert translator.translate('test', dest='ko')
assert translator.detect('Hello')