• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python microsofttranslator.Translator类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中microsofttranslator.Translator的典型用法代码示例。如果您正苦于以下问题:Python Translator类的具体用法?Python Translator怎么用?Python Translator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Translator类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: _meal

 def _meal(self, msg, *args):
     """Displays a 'enjoy your meal' message in a random language"""
     rand_lang = self._get_random_lang()
     meal = 'Enjoy your meal'
     translator = Translator(self._trans_client_id, self._trans_client_sec)
     translated = translator.translate(meal, rand_lang[0])
     return '{} (translated to {})'.format(translated, rand_lang[1])
开发者ID:rob19780114,项目名称:jabberbot,代码行数:7,代码来源:mucbot.py


示例2: translate

def translate(text, from_lang="zh", to_lang=None, max_nb_lines=None):
    u'''Translate to a different language. 
    Eg: '你好' becomes 'Hello'
    Only installed dictionaries can be used.

    to_lang possible values : CEDICT, HanDeDict, CFDICT,
    or 2-letter ISO language code for MS Translate
    
    if to_lang is unspecified, the default language will be used.
    '''
    global MS_translator_object
    if "" == text:
        return ""
    if None == to_lang:
        to_lang = chinese_support_config.options["dictionary"]
        if "None" == to_lang:
            return ""
    if to_lang in ["CEDICT", "CFDICT", "HanDeDict"]: #Local dict
        return translate_local(text, from_lang, to_lang, max_nb_lines)    
    else:  #Ms translate
        if None == MS_translator_object:
            MS_translator_object = MSTranslator("chinese-support-add-on", "Mh+X5YY17LZZ8rO9hzJXYD3I02V3E+ltItF15ep7qG8=")
        try:
            return MS_translator_object.translate(text, to_lang)
        except:
            return ""
开发者ID:chatch,项目名称:chinese-support-addon,代码行数:26,代码来源:edit_functions.py


示例3: __init__

class Mangle:
  
  def __init__(self):
    self.translator = Translator(client_id, client_secret) 
    self.langs = self.translator.get_languages()

  def mangle(self, message_text, language='en', times=0):

    # If they didn't specify, pick a random number of 
    #     times to scramble.
    if times == 0: times = random.randint(low, high)

    for i in range(times):

      rand_lang = random.choice(self.langs)

      message_text = self.translator.translate(message_text, 
                                          from_lang=language, 
                                          to_lang=rand_lang)

      message_text = self.translator.translate(message_text,
                                          from_lang=rand_lang,
                                          to_lang=language)

    return message_text
开发者ID:algidseas,项目名称:babble_bot,代码行数:25,代码来源:mangle.py


示例4: translate_text

def translate_text(request):
    language_from = request.GET.get('from', None)
    language_to = request.GET.get('to', None)
    text = request.GET.get('text', None)

    if language_from == language_to:
        data = {'success': True, 'translation': text}
    else:
        # run the translation:

        if getattr(rosetta_settings, 'GOOGLE_TRANSLATE', False):
            import goslate
            translator = goslate.Goslate()
        else:
            AZURE_CLIENT_ID = getattr(settings, 'AZURE_CLIENT_ID', None)
            AZURE_CLIENT_SECRET = getattr(settings, 'AZURE_CLIENT_SECRET', None)

            translator = Translator(AZURE_CLIENT_ID, AZURE_CLIENT_SECRET)

        try:
            translated_text = translator.translate(text, language_to, language_from)
            data = {'success': True, 'translation': translated_text}
        except TranslateApiException as e:
            data = {'success': False, 'error': "Translation API Exception: {0}".format(e.message)}

    return HttpResponse(json.dumps(data), content_type='application/json')
开发者ID:t0in4,项目名称:exgit,代码行数:26,代码来源:views.py


示例5: speakCaption

def speakCaption():
    filename = str(datetime.now()) + ".png"
    os.rename("./pepper_picture/now.png", "./pepper_picture/" + filename)

    print "Creating caption..."
    script = 'curl -F "[email protected]/pepper_picture/' + filename + '" localhost:8000'
    result = commands.getoutput(script).split("\n")[3]
    print result
    
    print "Translating..."
    translator = Translator('Your client ID', 'Your client secret') #change this line
    result = translator.translate(result, "ja")
    print result
    
    print "Creating wav.file with Rospeex and preparing speech..."
    tts_command = { "method":"speak",
                    "params":["1.1",
                    {"language":"ja","text":result,"voiceType":"*","audioType":"audio/x-wav"}]}
    
    obj_command = json.dumps(tts_command) # string to json object
    req = urllib2.Request(tts_url, obj_command)
    received = urllib2.urlopen(req).read() # get data from server
    
    obj_received = json.loads(received)
    tmp = obj_received['result']['audio'] # extract result->audio
    speech = base64.decodestring(tmp.encode('utf-8'))
    
    f = open ("./result_voice/out.wav",'wb')
    f.write(speech)
    f.close
    
    commands.getoutput('aplay ./result_voice/out.wav')
开发者ID:kiyomaro927,项目名称:NeuralPepper,代码行数:32,代码来源:node_runner.py


示例6: run_command

def run_command(msg, *args):
    """Displays a 'enjoy your meal' message in a random language"""
    lang_code, country = jabberbot.locale.random()
    meal = 'Enjoy your meal'
    translator = Translator(trans_client_id, trans_client_sec)
    translated = translator.translate(meal, lang_code)
    meal = '{} (translated to {})'.format(translated, country)
    return 'groupchat', meal
开发者ID:peterjuras,项目名称:jabberbot,代码行数:8,代码来源:meal.py


示例7: call_translate_method

 def call_translate_method(self, text, from_language, to_language):
     # This is supposed to be secret. I'm not really worried unless we distribute this thing.
     translator = Translator("HypeBot", "6QvARrt7O0/JPsUeNRDeixHIGozNb6O7Gd5cFjFLjYU=")
     if from_language == None:
         from_language = translator.detect_language(text=text)
     if to_language == None:
         to_language = 'en'  # Assume English
     return translator.translate(text=text, to_lang=to_language, from_lang=from_language)
开发者ID:JeffBorwey,项目名称:HypeBot,代码行数:8,代码来源:TranslateHandler.py


示例8: get

def get(parameter, channel, author, folder):
    if not parameter:
        return None
    params = parameter.split(" ",2)
    client = Translator(config.AZURE_CLIENT_ID, config.AZURE_CLIENT_SECRET)
    try:
        return client.translate(params[2].decode("utf-8"), params[1], from_lang=params[0]).encode("utf-8")
    except:
        return "Viga! Kasutamine: !trans lähtekeelekood sihtkeelekood tekst"
开发者ID:sviik,项目名称:marju2,代码行数:9,代码来源:__init__.py


示例9: send

def send():
    with sqlite3.connect("sample.db") as connection:
        c = connection.cursor()
        cht = request.form['msg']
        translator = Translator('rk', os.environ['CLIENT_KEY'])
        p = translator.translate(cht, "hi")
        t = time.strftime("%Y-%m-%d %H:%M:%S")
        c.execute("INSERT INTO chats(chat, time, name) VALUES(?, ?, ?)", (p, t,session.get('logged_in_user')))
    return "Ok"
开发者ID:rishikant42,项目名称:FlaskWebChatApp,代码行数:9,代码来源:chat3.py


示例10: MicrosoftTranslator

class MicrosoftTranslator(AbstractTranslator):
    name = "microsoft"

    def __init__(self):
        super(MicrosoftTranslator, self).__init__()
        if self.options is not None:
            client_id = self.options.get("client_id")
            client_secret = self.options.get("client_secret")
            if client_id is None or client_secret is None:
                raise ValueError(
                    "Misconfigured application. If you use the Microsoft Translator, provide a client_id and a client_secret"
                )
            self.client = MSTranslator(client_id=client_id, client_secret=client_secret)
        else:
            self.client = None

        self._languages = None

    @property
    def languages(self):
        if self._languages is not None:
            return self._languages
        if self.client is None:
            self._languages = []
        try:
            self._languages = self.client.get_languages()
        except MSTranslatorApiException:
            return []
        return self._languages

    def _translate(self, texts, language, origin_language="en"):
        """ [ 'Hello' ], 'es' => { 'Hello' : 'Hola' } """
        if self.client is None:
            return {}

        if language not in self.languages:
            return {}

        app.logger.debug("Translating %r to %r using Microsoft Translator API" % (texts, language))
        try:
            ms_translations = self.client.translate_array(texts=texts, to_lang=language, from_lang=origin_language)
        except MSTranslatorApiException as e:
            traceback.print_exc()
            app.logger.warn("Error translating using Microsoft Translator API: %s" % e, exc_info=True)
            return {}

        app.logger.debug("Translated %s sentences using Microsoft Translator API" % len(ms_translations))

        translations = {}
        for text, translation in zip(texts, ms_translations):
            translated_text = translation.get("TranslatedText")
            if translated_text:
                translations[text] = translated_text

        return translations
开发者ID:iasinDev,项目名称:appcomposer,代码行数:55,代码来源:suggestions.py


示例11: translate_bing

def translate_bing(text, in_lang, out_lang, bot):
    if not bot.config.has_option('translate', 'bing_user') or not bot.config.has_option('translate', 'bing_pass'):
        return 'No se ha habilitado el uso de bing en este bot!'
    else:
        user = bot.config.translate.bing_user
        password = bot.config.translate.bing_pass
    translator = Translator(user, password)
    if in_lang == 'auto':
       return translator.translate(text, out_lang)
    else:
       return translator.translate(text, out_lang, in_lang)
开发者ID:InteliBOT,项目名称:pyDreamBot,代码行数:11,代码来源:translate.py


示例12: post_request

def post_request():
    # request.formにPOSTデータがある
    source = request.form["source"]
    df=pd.read_csv("secret_bing_translate.csv", header=None)
    NAME_TRANS = df[0][0]
    KEY_TRANS = df[0][1]
    translator = Translator(NAME_TRANS, KEY_TRANS)
    to_lang = request.form["to_lang"]
    from_lang = request.form["from_lang"]
    result = translator.translate(source, to_lang, from_lang)
    global firstevent
    histories[source] = result
    return render_template('index.html', message="翻訳結果", source = source, result=result, histories = histories)
开发者ID:takechanman1228,项目名称:enjoy_bing_translate,代码行数:13,代码来源:bing_search.py


示例13: _birthday

    def _birthday(self, msg, *args):
        """Sends a happy birthday in an random language greeting

You can add a nickname: bday <nick>
        """
        rand_lang = self._get_random_lang()
        greet = 'Happy birthday to you'
        translator = Translator(self._trans_client_id, self._trans_client_sec)
        translated = translator.translate(greet, rand_lang[0])
        if args:
            return '{} @{} (translated to {})'.format(translated,
                                                      ' '.join(args),
                                                      rand_lang[1])
        return '{} (translated to {})'.format(translated, rand_lang[1])
开发者ID:rob19780114,项目名称:jabberbot,代码行数:14,代码来源:mucbot.py


示例14: MSTranslator

class MSTranslator():

    def __init__(self, client_id, client_secret):
        self.client_id = client_id
        self.client_secret = client_secret
        self.translator = Translator(client_id, client_secret)

    def detect(self, text):
        code = self.translator.detect_language(text)
        lang = Language(code)
        return lang

    def translate(self, text, target_lang="ja"):
        translated_text = self.translator.translate(text, target_lang)
        return translated_text
开发者ID:tominaga443,项目名称:globalbot,代码行数:15,代码来源:mstranslator.py


示例15: __init__

class BingTranslator:
    def __init__(self):
        client_id = os.environ.get("BING_TRANSLATION_CLIENT_ID", "gigaware123")
        client_secret = os.environ.get("BING_TRANSLATION_SECRET", "Dp3afp41sR/sDsKRK3uWPt2i4WbAKqKB5q6RhCI9a1Q=")

        if not client_id or not client_secret:
            raise Exception("bing translation client id or client secret not found")

        self.translator = Translator(client_id, client_secret)

    def translate(self, untranslated, target_language):
        return self.translator.translate(untranslated, target_language, from_lang='en')

    def translate_all(self, untranslated, target_language):
        return self.translator.translate_array(untranslated, target_language, from_lang='en')
开发者ID:shaiwilson,项目名称:gig,代码行数:15,代码来源:bing_translator.py


示例16: run_command

def run_command(msg, *args):
    """Sends a happy birthday in an random language greeting

You can add a nickname: bday <nick>
    """
    lang_code, country = jabberbot.locale.random()
    greet = 'Happy birthday to you'
    translator = Translator(trans_client_id, trans_client_sec)
    translated = translator.translate(greet, lang_code)
    mtype = 'groupchat'
    if args:
        return mtype, '{} @{} (translated to {})'.format(
            translated,
            ' '.join(args),
            country)
    return mtype, '{} (translated to {})'.format(translated, country)
开发者ID:peterjuras,项目名称:jabberbot,代码行数:16,代码来源:bday.py


示例17: test_get_traslations

    def test_get_traslations(self):
        client = Translator(client_id, client_secret, debug=True)
        self.assertEqual(
            client.get_translations("sun", "ru"),
            {'From': 'en', 'Translations': [
                {'Rating': 5, 'TranslatedText': u'Солнце', 'Count': 0, 'MatchDegree': 100, 'MatchedOriginalText': ''},
                {'Rating': 1, 'TranslatedText': u'Солнце', 'Count': 1, 'MatchDegree': 100, 'MatchedOriginalText': 'sun'},
                {'Rating': 1, 'TranslatedText': u'солнце', 'Count': 1, 'MatchDegree': 100, 'MatchedOriginalText': 'sun'},
                {'Rating': 1, 'TranslatedText': u'ВС', 'Count': 1, 'MatchDegree': 99, 'MatchedOriginalText': 'SUN'},
                {'Rating': 1, 'TranslatedText': u'Вос', 'Count': 1, 'MatchDegree': 99, 'MatchedOriginalText': 'Sun'},
                {'Rating': 1, 'TranslatedText': u'Воскресенье', 'Count': 1, 'MatchDegree': 99, 'MatchedOriginalText': 'Sun'},
                {'Rating': 1, 'TranslatedText': u'Вс', 'Count': 1, 'MatchDegree': 99, 'MatchedOriginalText': 'Sun'},
                {'Rating': 0, 'TranslatedText': u'СОЛНЦЕ!!', 'Count': 0, 'MatchDegree': 63, 'MatchedOriginalText': 'SUN!!'}
            ]}

        )
开发者ID:kz20,项目名称:Microsoft-Translator-Python-API,代码行数:16,代码来源:test.py


示例18: translate

def translate(entities):
    phrase_to_translate = entities.get('phrase_to_translate')[0].get('value')
    message = ""
    if entities.get('language') == None:
        message = "Language not supported"
    else:
        language = entities.get('language')[0].get('value')
        language = language.lower()
        if language == "chinese" or language == "zh-CHS":
            language = "zh-CHS"
        elif language == "dutch" or language == "nl":
            language = "nl"
        elif language == "english" or language == "en":
            language = "en"
        elif language == "french" or language == "fr":
            language = "fr"
        elif language == "german" or language == "de":
            language = "de"
        elif language == "italian" or language == "it":
            language = "it"
        elif language == "japanese" or language == "ja":
            language = "ja"
        elif language == "korean" or language == "ko":
            language = "ko"
        elif language == "portuguese" or language == "pt":
            language = "pt"
        elif language == "russian" or language == "ru":
            language = "ru"
        elif language == "spanish" or language == "es":
            language = "es"
        elif language == "swedish" or language == "sv":
            language = "sv"
        elif language == "thai" or language == "th":
            language = "th"
        elif language == "vietnamese" or language == "vi":
            language = "vi"
        else:
            message = "Language not supported"
    if message != "Language not supported":
        translator = Translator('SMSAssistant', 'fhV+AdYFiK0QfQ4PFys+oQ/T0xiBBVQa32kxxbP55Ks=')
        message = translator.translate(phrase_to_translate, language)
    resp = twilio.twiml.Response()
    # print message
    resp.message(message)
    return resp
开发者ID:nelson-liu,项目名称:SMSiri,代码行数:45,代码来源:server.py


示例19: translate

def translate(text, from_lang="zh", to_lang=None, progress_bar=True):
    u'''Translate to a different language. 
    Eg: '你好' becomes 'Hello'
    Only installed dictionaries can be used.

    to_lang possible values : "local_en", "local_de", "local_fr"
    or a 2-letter ISO language code for MS Translate
    
    if to_lang is unspecified, the default language will be used.
    if progress_bar is True, then will display a progress bar.
    '''
    global MS_translator_object
    text = cleanup(text)
    if "" == text:
        return ""
    if None == to_lang:
        to_lang = chinese_support_config.options["dictionary"]
        if "None" == to_lang:
            return ""
    if to_lang.startswith("local_"): #Local dict
        return translate_local(text, to_lang[-2:])
    else:  #Ms translate
        ret = ""
        if progress_bar:
            mw.progress.start(label="MS Translator lookup", immediate=True)
        if None == MS_translator_object:
            MS_translator_object = MSTranslator("chinese-support-add-on", "Mh+X5YY17LZZ8rO9hzJXYD3I02V3E+ltItF15ep7qG8=")
        try:
            ret = MS_translator_object.translate(text, to_lang)
        except:
            pass
        
        if "ArgumentException:" == ret[:18]:
            #Token has probably expired
            ret=""
        if progress_bar:
            mw.progress.finish()
        return ret
开发者ID:Varbird,项目名称:chinese-support-addon,代码行数:38,代码来源:edit_functions.py


示例20: translate

def translate():
	#missingword = request.form['missingword']
	#to_language = request.form['to_language']
	missingword = 'envelope'
	to_language = 'ja'
	#from_language = request.form['from_language']

	#翻訳
	print '1step'
	translator = Translator('skeven', 'vizaHdZEjZkP0ZdL/B3CQ0UO9yzsgmTT2hDtuvJFdL0=')
	# from_languageは自動的に判別されるので指定する必要が無い
	translated_word = translator.translate(missingword, to_language)
	print '2step'
	#translated_word = translator.translate("Hello", "ja")
	# Registering Word to DB(CSV?)
	languagetype = translator.detect_language(missingword)
	print '3step'

	inlinecsv = languagetype + '$YIN$' + missingword + '$YIN$' + to_language + "$YIN$" + translated_word + '\n'
	print inlinecsv
	f = open('./word/addinfo_dictionary_utf8.txt', 'a')
	f.write(inlinecsv.encode('utf-8'))
	f.close()
	return translated_word;
开发者ID:ShoSekine,项目名称:HONYAC,代码行数:24,代码来源:fileuploader.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python service.ValidationErrors类代码示例发布时间:2022-05-27
下一篇:
Python middleware.MicrositeConfiguration类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap