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


Python Translator.translate_array方法代码示例

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


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

示例1: MicrosoftTranslator

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

示例2: __init__

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

示例3: crawlCourseEssence

# 需要导入模块: from microsofttranslator import Translator [as 别名]
# 或者: from microsofttranslator.Translator import translate_array [as 别名]
def crawlCourseEssence(course_list):
	url = "https://course.ncu.edu.tw/Course/main/query/byKeywords?"
	#ex: https://course.ncu.edu.tw/Course/main/query/byKeywords?serialNo=11001&outline=11001&semester=1031
	course_essence_list = []
	de = DepEssence()
	objective_buffer = []
	ob = 0
	content_buffer = []
	content_ch_buffer = []
	cb = 0
	translator = Translator('21KRtranslator', '1VYijs8FLyy7wmD/x1KsSWficJPiH61jywgGBM5m+iA=')
	for i, c in enumerate(course_list):
		if (i==0):
			de.id = str(c.category.id)
			de.category = c.category
			de.course_tree = c.leaf_of
			course_essence_list = []
		params = urllib.urlencode({'serialNo': c.serial_no, 'outline': c.serial_no, 'semester': c.semester})
		#dom = requests.get(url=url, params=params, headers={'Cookie': 'JSESSIONID=7257F09EDF368A37341694B4A4D7B72E', 'Accept-Language': 'zh-tw,zh;q=0.8,en-us;q=0.5,en;q=0.3', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:31.0) Gecko/20100101 Firefox/31.0'})
		dom = pq(url=url+params, headers={'Cookie': 'JSESSIONID=7257F09EDF368A37341694B4A4D7B72E', 'Accept-Language': 'zh-tw,zh;q=0.8,en-us;q=0.5,en;q=0.3', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:31.0) Gecko/20100101 Firefox/31.0'})
		raw = dom('script').text().encode('utf_8').decode('unicode_escape').split('\';')[0].replace('var JData = \'', '')
		data = json.loads(raw)
		try:
			if(data['msg']==u'notfound'):continue
		except KeyError:
			ce = CourseEssence()
			ce.id = c.id
			ce.course = c
			ce.course_tree = c.leaf_of
			ce.category = c.category
			ce.objective = unicode(data['courseObject']).replace(' ', ' ')
			ce.content = unicode(data['courseContent']).replace(' ', ' ')
			objective_buffer.append(ce.objective)
			content_buffer.append(ce.content)
			#return translator.translate_array(content_buffer, 'zh-CHT')
			ce.ability_list = []
			
			for m in data['courseMap']:
				if(m['strength']==u'N/A'):continue
				ability = CoreAbility(ability=unicode(m['core']), rating=m['strength'][1:2], evaluation=unicode(m['testType'])[0:-1].split(','))
				ce.ability_list.append(ability)

			course_essence_list.append(ce)
		
	
	i=0
	p = re.compile(ur'(\(\d*/\d*\))|(\d+\.)|(\d)|(<br/>)|(\([a-z]+\-[a-z]+\))|(\([a-z]+\-[a-z]+\s[a-z]+\))|()|(•)|(gt)|(^lt)|(\d*/\d*)|(败)|(^I{1,3})')
	while(i<=len(content_buffer)):
		min = 4 if (len(content_buffer)-i >= 4) else len(content_buffer)-i
		tmp_cont = translator.translate_array(content_buffer[i:i+min], 'en')
		#tmp_obj = translator.translate_array(objective_buffer[i:i+min], 'en')
		j=0
		for ce in course_essence_list[i:i+min]:
			ce.content_en = p.sub('', tmp_cont[j]['TranslatedText'])
			#ce.objective_en = tmp_obj[j]['TranslatedText']
			#ce.save()
			j+=1
		i+=5

	i=0
	while(i<=len(objective_buffer)):
		min = 4 if (len(objective_buffer)-i >= 4) else len(objective_buffer)-i
		#tmp_cont = translator.translate_array(content_buffer[i:i+min], 'en')
		tmp_obj = translator.translate_array(objective_buffer[i:i+min], 'en')
		j=0
		for ce in course_essence_list[i:i+min]:
			#ce.content_en = tmp_cont[j]['TranslatedText']
			ce.objective_en = p.sub('', tmp_obj[j]['TranslatedText'])
			ce.save()
			j+=1
		i+=5
	de.course_essence_list = course_essence_list
	de.save()
	return course_essence_list
开发者ID:NCUNOS,项目名称:two_one_kr,代码行数:76,代码来源:crawler.py


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