當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。