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


Python Translator.get_languages方法代码示例

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


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

示例1: __init__

# 需要导入模块: from microsofttranslator import Translator [as 别名]
# 或者: from microsofttranslator.Translator import get_languages [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: MicrosoftTranslator

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

示例3: test_get_languages

# 需要导入模块: from microsofttranslator import Translator [as 别名]
# 或者: from microsofttranslator.Translator import get_languages [as 别名]
 def test_get_languages(self):
     client = Translator(client_id, client_secret, debug=True)
     languages = client.get_languages()
     self.assertEqual(type(languages), list)
     self.assertTrue(set(default_languages).issubset(set(languages)))
开发者ID:kz20,项目名称:Microsoft-Translator-Python-API,代码行数:7,代码来源:test.py

示例4: main

# 需要导入模块: from microsofttranslator import Translator [as 别名]
# 或者: from microsofttranslator.Translator import get_languages [as 别名]
def main():
    parser = argparse.ArgumentParser(description='Automatically translate and synchronize .strings files from defined base language.')
    parser.add_argument('-b','--base-lang-name', help='A base(or source) localizable resource name.(default=\'Base\'), (e.g. "Base" via \'Base.lproj\', "en" via \'en.lproj\')', default='Base', required=False)
    parser.add_argument('-x','--excluding-lang-names', type=str, help='A localizable resource name that you want to exclude. (e.g. "Base" via \'Base.lproj\', "en" via \'en.lproj\')', default=[], required=False, nargs='+')
    parser.add_argument('-c','--client-id', help='Client ID for MS Translation API', required=True)
    parser.add_argument('-s','--client-secret', help='Client Secret key for MS Translation API', required=True)
    parser.add_argument('-f','--force-translate-keys', type=str, help='Keys in the strings to update and translate by force. (input nothing for all keys.)', default=[], required=False, nargs='*')
    parser.add_argument('-fb','--following-base-keys', type=str, help='Keys in the strings to follow from "Base".', default=[], required=False, nargs='+')
    parser.add_argument('target path', help='Target localizable resource path. (root path of Base.lproj, default=./)', default='./', nargs='?')
    args = vars(parser.parse_args())

    reload(sys)
    sys.setdefaultencoding('utf-8')

    # configure arguments
    __LANG_SEP__ = '-'
    __DIR_SUFFIX__ = ".lproj"
    __FILE_SUFFIX__ = ".strings"
    __RESOURCE_PATH__ = expanduser(args['target path'])
    __BASE_LANG__ = args['base_lang_name']
    __EXCLUDING_LANGS__ = args['excluding_lang_names']
    __KEYS_FORCE_TRANSLATE__ = args['force_translate_keys']
    __KEYS_FORCE_TRANSLATE_ALL__ = ('--force-translate-keys' in sys.argv or '-f' in sys.argv) and not __KEYS_FORCE_TRANSLATE__
    __KEYS_FOLLOW_BASE__ = args['following_base_keys']
    __BASE_RESOUCE_DIR__ = None

    __LITERNAL_FORMAT__ = "%@"
    __LITERNAL_FORMAT_RE__ = re.compile(r"(%\s{1,}@)|(@\s{0,}%)")
    __LITERNAL_REPLACEMENT__ = "**"
    __LITERNAL_REPLACEMENT_RE__ = re.compile(r"\*\s{0,}\*")

    __QUOTES_RE__ = re.compile(r"\"")
    __QUOTES_REPLACEMENT__ = "'"

    if __BASE_LANG__.endswith(__DIR_SUFFIX__):
        __BASE_RESOUCE_DIR__ = __BASE_LANG__
        __BASE_LANG__ = __BASE_LANG__.split(__DIR_SUFFIX__)[0]
    else:
        __BASE_RESOUCE_DIR__ = __BASE_LANG__+__DIR_SUFFIX__

    # setup Translator & langs

    # read ios langs
    print '(i) Fetching supported locale codes for ios9 ...'
    __IOS9_CODES__ = [lang_row[0] for lang_row in csv.reader(open(resolve_file_path('lc_ios9.tsv'),'rb'), delimiter='\t')]
    print '(i) Supported numbers of locale code :', len(__IOS9_CODES__)

    __MS_CODE_ALIASES__ = {
        # MS API Supported : ios9 supported ISO639 1-2 codes
        'zh-CHS' : ['zh-Hans', 'zh-CN', 'zh-SG'],
        'zh-CHT' : ['zh-Hant', 'zh-MO', 'zh-HK', 'zh-TW'],
        'en' : ['en-AU', 'en-GB'],
        'es' : ['es-MX'],
        'fr' : ['fr-CA'],
        'pt' : ['pt-BR','pt-PT']
    }

    # read mst langs
    print '(i) Fetching supported locales from Microsoft Translation API...'
    trans = Translator(args['client_id'], args['client_secret'])

    __MS_LANG_FILE__ = resolve_file_path('lc_ms.cached.tsv')
    __MS_SUPPORTED_CODES__ = None
    if os.path.exists(__MS_LANG_FILE__):
        __MS_SUPPORTED_CODES__ = [l.strip() for l in open(__MS_LANG_FILE__,'rb').readlines()]
    else:
        __MS_SUPPORTED_CODES__ = trans.get_languages()
        cfile = open(__MS_LANG_FILE__,'w')
        codes = ''
        for code in __MS_SUPPORTED_CODES__:
            codes += code+'\n'
        cfile.write(codes)
        cfile.close()
    print '(i) Supported numbers of locale code :', len(__MS_SUPPORTED_CODES__)

    # methods
    def supported_lang(code):
        alias = [ms for ms, ios in __MS_CODE_ALIASES__.items() if code in ios]
        # check es-{Custom defined alias}
        if len(alias)==1:
            return alias[0]
        # check es-MX
        elif code in __MS_SUPPORTED_CODES__:
            return code
        # check es
        elif code.split(__LANG_SEP__)[0] in __MS_SUPPORTED_CODES__:
            return code.split(__LANG_SEP__)[0]
        else:
            return None

    def preprocessing_translate_strs(strs):
        return [__LITERNAL_FORMAT_RE__.sub(__LITERNAL_FORMAT__, s.strip()).replace(__LITERNAL_FORMAT__, __LITERNAL_REPLACEMENT__) for s in strs]

    def postprocessing_translate_str(str):
        str = str.strip()
        # remove Quotes
        str = __QUOTES_RE__.sub(__QUOTES_REPLACEMENT__, str)
        # replace tp liternal replacement
        str = validate_liternal_replacement(str)
        # liternal replacement to liternal for format
#.........这里部分代码省略.........
开发者ID:chapayGhub,项目名称:strsync,代码行数:103,代码来源:strsync.py

示例5: Translator

# 需要导入模块: from microsofttranslator import Translator [as 别名]
# 或者: from microsofttranslator.Translator import get_languages [as 别名]
     else:
         global commandPrefix
         message.Chat.SendMessage('Changed the command prefix from "%s" to "%s".' % (commandPrefix, arguments[1]))
         commandPrefix = arguments[1]
      
 elif arguments[0] == 'reboot':
     message.Chat.SendMessage('Attempting reboot...')
     try:
         os.execv(__file__, sys.argv)
     except Exception, error:
         message.Chat.SendMessage('There was an error: %s' % error)
         
 elif arguments[0] == 'translate':
     translator = Translator('JEREMY-skype-bot', 'iEvV4ZWgMjAM45Jub+WHXHHI9CZ4QJspduxTrFOXrkc=')
     if arguments[1] == 'get-langs':
         languages = translator.get_languages()
         message.Chat.SendMessage(', '.join(languages.sort()))
     elif arguments[1] == 'detect':
         langOut = arguments[2]
         restOfMessage = arguments
         del restOfMessage[0]
         del restOfMessage[1]
         del restOfMessage[2]
         messageToTranslate = ' '.join(restOfMessage)
         try:
             translatedMessage = translator.translate(messageToTranslate, langOut)
             message.Chat.SendMessage('Language detected: ' + translator.translate(messageToTranslate)
              + '\nLanguage to translate to: ' + langOut
              + '\nMessage to translate: ' + messageToTranslate
              + '\nTranslated message: ' + translatedMessage)
         except Exception, error:
开发者ID:michaelgira23,项目名称:JEREMY,代码行数:33,代码来源:JEREMY.py


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