当前位置: 首页>>代码示例>>Python>>正文


Python googletrans.Translator方法代码示例

本文整理汇总了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() 
开发者ID:learnpyqt,项目名称:15-minute-apps,代码行数:20,代码来源:translate.py

示例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) 
开发者ID:ssut,项目名称:py-googletrans,代码行数:24,代码来源:translate_word_doc.py

示例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)) 
开发者ID:the-ethan-hunt,项目名称:B.E.N.J.I.,代码行数:27,代码来源:google_translator.py

示例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() 
开发者ID:taseikyo,项目名称:PyQt5-Apps,代码行数:22,代码来源:main.py

示例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 
开发者ID:taseikyo,项目名称:PyQt5-Apps,代码行数:18,代码来源:main.py

示例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 
开发者ID:eliranwong,项目名称:UniqueBible,代码行数:23,代码来源:Languages.py

示例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))) 
开发者ID:eliranwong,项目名称:UniqueBible,代码行数:19,代码来源:Languages.py

示例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 
开发者ID:AdultScraperX,项目名称:AdultScraperX-server,代码行数:19,代码来源:main.py

示例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) 
开发者ID:bzantium,项目名称:chatbot-seminar,代码行数:7,代码来源:telegram_bot.py

示例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 
开发者ID:xingag,项目名称:tools_python,代码行数:10,代码来源:main.py

示例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 
开发者ID:HoussemCharf,项目名称:FunUtils,代码行数:6,代码来源:tradutor.py

示例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) 
开发者ID:sukeesh,项目名称:Jarvis,代码行数:16,代码来源:translate.py

示例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) 
开发者ID:doncat99,项目名称:StockRecommendSystem,代码行数:16,代码来源:Fetch_Data_News_US.py

示例14: translator

# 需要导入模块: import googletrans [as 别名]
# 或者: from googletrans import Translator [as 别名]
def translator():
    from googletrans import Translator
    return Translator() 
开发者ID:ssut,项目名称:py-googletrans,代码行数:5,代码来源:conftest.py

示例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') 
开发者ID:ssut,项目名称:py-googletrans,代码行数:13,代码来源:test_client.py


注:本文中的googletrans.Translator方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。