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


Python Translator.translate方法代码示例

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


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

示例1: __init__

# 需要导入模块: from microsofttranslator import Translator [as 别名]
# 或者: from microsofttranslator.Translator import translate [as 别名]
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,代码行数:27,代码来源:mangle.py

示例2: translate_bing

# 需要导入模块: from microsofttranslator import Translator [as 别名]
# 或者: from microsofttranslator.Translator import translate [as 别名]
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,代码行数:13,代码来源:translate.py

示例3: translate_text

# 需要导入模块: from microsofttranslator import Translator [as 别名]
# 或者: from microsofttranslator.Translator import translate [as 别名]
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,代码行数:28,代码来源:views.py

示例4: speakCaption

# 需要导入模块: from microsofttranslator import Translator [as 别名]
# 或者: from microsofttranslator.Translator import translate [as 别名]
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,代码行数:34,代码来源:node_runner.py

示例5: translate

# 需要导入模块: from microsofttranslator import Translator [as 别名]
# 或者: from microsofttranslator.Translator import translate [as 别名]
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,代码行数:28,代码来源:edit_functions.py

示例6: _meal

# 需要导入模块: from microsofttranslator import Translator [as 别名]
# 或者: from microsofttranslator.Translator import translate [as 别名]
 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,代码行数:9,代码来源:mucbot.py

示例7: call_translate_method

# 需要导入模块: from microsofttranslator import Translator [as 别名]
# 或者: from microsofttranslator.Translator import translate [as 别名]
 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,代码行数:10,代码来源:TranslateHandler.py

示例8: run_command

# 需要导入模块: from microsofttranslator import Translator [as 别名]
# 或者: from microsofttranslator.Translator import translate [as 别名]
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,代码行数:10,代码来源:meal.py

示例9: get

# 需要导入模块: from microsofttranslator import Translator [as 别名]
# 或者: from microsofttranslator.Translator import translate [as 别名]
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,代码行数:11,代码来源:__init__.py

示例10: send

# 需要导入模块: from microsofttranslator import Translator [as 别名]
# 或者: from microsofttranslator.Translator import translate [as 别名]
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,代码行数:11,代码来源:chat3.py

示例11: post_request

# 需要导入模块: from microsofttranslator import Translator [as 别名]
# 或者: from microsofttranslator.Translator import translate [as 别名]
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,代码行数:15,代码来源:bing_search.py

示例12: _birthday

# 需要导入模块: from microsofttranslator import Translator [as 别名]
# 或者: from microsofttranslator.Translator import translate [as 别名]
    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,代码行数:16,代码来源:mucbot.py

示例13: __init__

# 需要导入模块: from microsofttranslator import Translator [as 别名]
# 或者: from microsofttranslator.Translator import translate [as 别名]
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,代码行数:17,代码来源:bing_translator.py

示例14: MSTranslator

# 需要导入模块: from microsofttranslator import Translator [as 别名]
# 或者: from microsofttranslator.Translator import translate [as 别名]
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,代码行数:17,代码来源:mstranslator.py

示例15: run_command

# 需要导入模块: from microsofttranslator import Translator [as 别名]
# 或者: from microsofttranslator.Translator import translate [as 别名]
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,代码行数:18,代码来源:bday.py


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