本文整理匯總了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')