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


Python Translator.translate方法代码示例

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


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

示例1: twist

# 需要导入模块: from translate import Translator [as 别名]
# 或者: from translate.Translator import translate [as 别名]
	def twist(self, in_message):
		start_lang = 'en'
		last_lang = 'en'
		sentence =  in_message
		turns = 20

		first_step = ''

		for lang in range(len(lang_array)):
			if start_lang == lang_array[lang][1]:
				first_step += (lang_array[lang][0])

		steps = []
		for turn in range(turns):
			rand_int = r.randint(0,len(lang_array)-1)
			rand_lang = lang_array[rand_int][1]
			translator = Translator(to_lang = rand_lang, from_lang = last_lang)
			sentence = translator.translate(sentence)
			if sys.version_info.major == 2:
				sentence =sentence.encode(locale.getpreferredencoding())
			steps.append([sentence, rand_lang])
			print(str(turn + 1)+ '/' + str(turns) + ' (' + lang_array[rand_int][0] + ')')
			last_lang = rand_lang
		translator = Translator(to_lang = start_lang, from_lang = last_lang)
		sentence = translator.translate(sentence)
		sentence = sentence.capitalize()
		sentence = sentence.replace(' ,', ',')
		sentence = sentence.replace(' .', '.')
		sentence = sentence.replace(' \'', '\'')
		if sentence[len(sentence) - 1] != '.':
			sentence += '.'
		# print('\n' + steps)
		# print('\n' + sentence)
		return [steps, sentence]
开发者ID:rkram5424,项目名称:Babelrang,代码行数:36,代码来源:Babelrang.py

示例2: translate_excel

# 需要导入模块: from translate import Translator [as 别名]
# 或者: from translate.Translator import translate [as 别名]
def translate_excel():
    outfile = open("english_cv.md",'w')
    
    translator= Translator(from_lang="zh",to_lang="en")

    # sXXX for SOURCExxx
    sbook = open_workbook('source.xls',formatting_info= False )
    # tXXX means translatedXXX
    tbook = Workbook(encoding='utf-8')#write
    
    # read and write per sheet
    book_content = []
    for s in sbook.sheets():# s is a source sheet handle for read
        
        #add sheet
        try:
            utf_name = s.name.encode('utf8') #sheet names are all in unicode, translation need utf8
            tsheet_name = translator.translate(utf_name) #translator.translate method only accepts utf-8
            print s.name,tsheet_name
            tsheet = tbook.add_sheet(tsheet_name) # write sheet in tbook, name in english
            print_title(tsheet_name,outfile)#write
        except:
            print "error in sheet:",s.name,"\n"
            print_title(s.name,outfile)
            
        #add content
        
        rows_content = []
        for row in range(s.nrows):
            print "row:",row
            col_content = []
            for col in range(s.ncols):
                try:
                    utf_cell = s.cell(row,col).value.encode('utf8')
                    tcell_value = translator.translate(utf_cell)
                    tsheet.write(row,col,tcell_value)
                    col_content.append(tcell_value)
                except: #the value might be float
                    # print "row:",row,"col:",col,s.cell(row,col).value
                    # tsheet.write(row,col,s.cell(row,col).value)
                    
                    nontexts = s.cell(row,col).value
                    col_content.append(str(nontexts))
            row_value = "\t".join(col_content)
            rows_content.append(row_value)
            tsheet.flush_row_data()
            
        try:
            sheet_txt = "\n".join(rows_content).encode('utf8')
        except:
            sheet_txt = "\n".join(rows_content)
        all_lines = invert_txt_table(sheet_txt)
        print_table(all_lines,outfile)

    outfile.close()
    
    print "saving..."
    tbook.save('english_output.xls')
    print "saved."
开发者ID:redreamality,项目名称:CV-toy,代码行数:61,代码来源:excel_translator.py

示例3: main

# 需要导入模块: from translate import Translator [as 别名]
# 或者: from translate.Translator import translate [as 别名]
def main():
    arguements = docopt(
        data_io.set_up_doc(__doc__),
        version='0.1'
    )

    record = Record(debug=arguements['--debug'])
    if arguements['<data>']:
        # translation
        from_lang, to_lang, data = _extract(arguements)

        # translate data
        translator = Translator(from_lang, to_lang, data,
                                debug=arguements['--debug'])
        # result is a dictionary contains decoded infomation of the
        # trnaslation.
        result = translator.translate()
        translator.display_result(result)
        # add record
        record.add(from_lang, to_lang,
                   data, result)

    elif arguements['--record']:
        # display record
        record.display()
    else:
        raise Exception('No Implemented Yet.')
开发者ID:ftao,项目名称:MyGoogleDict,代码行数:29,代码来源:interface.py

示例4: process

# 需要导入模块: from translate import Translator [as 别名]
# 或者: from translate.Translator import translate [as 别名]
def process(source, outfile, _filter):
    if os.path.isfile(source):
        deny = []
        with open(_filter, 'r') as filter:
            for line in filter:
                deny.append(line.replace('\n', '').replace('\r', ''))
        tmp = []
        words = {}
        with open(source, 'r') as source:
            with open(outfile, 'w') as dic:
                for str in source:
                    tmp = normalize(str).split(' ')
                    for word in tmp:
                        if len(word) > 2:
                            if words.get(word):
                                words[word] += 1
                            else:
                                words[word] = 1
                # print words
                translator = Translator(to_lang="ru")
                for key, value in sorted(words.iteritems(), key=lambda (k, v): (v, k)):
                    if key not in deny:
                        dic.write(key + ' - ' + translator.translate(key).encode("utf8") + '\n')
                        # print "%s: %s" % (key, value)
    else:
        print 'Plese input correctly data for <source>!'
开发者ID:WoLfh0UnD,项目名称:English,代码行数:28,代码来源:createDic.py

示例5: trans

# 需要导入模块: from translate import Translator [as 别名]
# 或者: from translate.Translator import translate [as 别名]
def trans(flag,lang,word,delim):
  try:
    langNAme,langReq = word.split(delim,1)
    length=len(langReq)
    if ( length > maxLength):
      sc.api_call('chat.postMessage', 
                   username='botiana', 
                   icon_url=flag,  
                   as_user='false', 
                   channel=evt["channel"], 
                   text='Don\'t be a dick <@'+evt["user"]+'>')
    else:
      translator= Translator(to_lang=lang)
      l = translator.translate(langReq)
      sc.api_call('chat.postMessage', 
                   username='botiana', 
                   icon_emoji=flag,
                   as_user='false', 
                   channel=evt["channel"], 
                   text=l)
  except ValueError:
    sc.api_call('chat.postMessage', 
                 username='botiana', 
                 icon_url=flag,
                 as_user='false', 
                 channel=evt["channel"], 
                 text='Vhy try to anger botiana <@'+evt["user"]+'>?')
开发者ID:kkochis,项目名称:botiana,代码行数:29,代码来源:botiana.py

示例6: ask_mapping

# 需要导入模块: from translate import Translator [as 别名]
# 或者: from translate.Translator import translate [as 别名]
def ask_mapping(token_list):
    "Asks the user for a mapping"
    translation_name = input('Enter code of target language("hi" for hindi): ')
    translation_name = translation_name.upper().strip()
    translator = Translator(to_lang=translation_name)
    mapping = {}
    for token in token_list:
        internal = False
        if token[:2] + token[-2:] == '____':
            token = token[2:-2]
            internal = True
        try:
            translation = translator.translate(token)
        except:
            print('>'*10, 'Token failed to translate :|', token + '|')
        translation = translation.replace(' ', '_').strip()
        if internal:
            token = '__' + token + '__'
            translation = '__' + translation + '__'
        mapped = {translation: token}
        print(mapped)
        mapping.update(mapped)
    f = open(translation_name, 'w')
    f.write(json.dumps(mapping,
                       ensure_ascii=False,
                       indent=4))
    f.close()
开发者ID:Semelamar,项目名称:pytongue,代码行数:29,代码来源:map_generator.py

示例7: TestTranslator

# 需要导入模块: from translate import Translator [as 别名]
# 或者: from translate.Translator import translate [as 别名]
class TestTranslator(unittest.TestCase):

    client_id = "<CLIENT_ID>"
    client_secret = "<CLIENT_SECRET>"

    def setUp(self):
        self.t = Translator(self.client_id, self.client_secret)

    def test_get_access_token(self):
        self.assertNotEqual(self.t.get_access_token(), "", "The access token is empty!")

    def test_translate(self):
        translated = self.t.translate("day", "en", "it")
        self.assertEqual(translated.lower(), "giorno", "The translated word is incorrect!")

        translated = self.t.translate("summer", "en", "ro")
        self.assertEqual(translated.lower(), "vara", "The translated word is incorrect!")
开发者ID:dansul,项目名称:Translator,代码行数:19,代码来源:tests.py

示例8: trans_to_english

# 需要导入模块: from translate import Translator [as 别名]
# 或者: from translate.Translator import translate [as 别名]
def trans_to_english(sentence, language):
    """
    Translate a sentece to English.
    """
    translator= Translator(from_lang=language, to_lang="en")
    translation = translator.translate(sentence)
    print(translation)
    return translation
开发者ID:DataKind-SG,项目名称:anti_corruption_network,代码行数:10,代码来源:clean_thai_procurement_data.py

示例9: translate

# 需要导入模块: from translate import Translator [as 别名]
# 或者: from translate.Translator import translate [as 别名]
def translate(string, fromlang, tolang):
    translator = Translator(from_lang=fromlang, to_lang=tolang)
    print "Translating from " + fromlang + " to " + tolang
    try:
        return translator.translate(string).encode("UTF-8")
    except Exception as e:
        print "HTTP Error. Translation failed. Please run the script again."
        sys.exit()
开发者ID:sserenade,项目名称:scripts,代码行数:10,代码来源:iamgomen.py

示例10: index

# 需要导入模块: from translate import Translator [as 别名]
# 或者: from translate.Translator import translate [as 别名]
def index(request, source, target, text):
    trans = Translator(to_lang=target, from_lang=source)
    translation = trans.translate(text)
    # return HttpResponse(translation)

    return HttpResponse("""{ "data": { "translations": [ { "translatedText": "%s" } ] } }""" % translation)

# def index(request, text, source, target):
#     return HttpResponse("Hello, world. You're at the polls index.")
开发者ID:egslava,项目名称:translator-server,代码行数:11,代码来源:views.py

示例11: trans

# 需要导入模块: from translate import Translator [as 别名]
# 或者: from translate.Translator import translate [as 别名]
def trans(request):
    if request.method == 'POST':
        inpu = request.POST.get('intext', '')
        translator= Translator(to_lang="fr")
        out = translator.translate(str(inpu))
        print out
        return HttpResponse(out)
    else:
         return render(request, 'personal/header.html')
开发者ID:Frankkwizera,项目名称:Django_Translator,代码行数:11,代码来源:views.py

示例12: __trans

# 需要导入模块: from translate import Translator [as 别名]
# 或者: from translate.Translator import translate [as 别名]
def __trans(flag, lang, message):
    try:
        if len(message) > MAX_TRANSLATE_LENGTH:
            resp = "Don't be a dick <@{}>".format(evt["user"])
            __send_response(resp, icon_ru)
        else:
            translator = Translator(to_lang=lang)
            l = translator.translate(message)
            __send_response(l, "emoji", flag)
    except ValueError:
        resp = 'Vhy try to anger {} <@{}>?'.format(BOT_NAME, evt["user"])
        __send_response(resp, icon_ru)
开发者ID:elementalvoid,项目名称:botiana,代码行数:14,代码来源:botiana.py

示例13: generate_release_names

# 需要导入模块: from translate import Translator [as 别名]
# 或者: from translate.Translator import translate [as 别名]
def generate_release_names(num, names, translate=True, show_excluded=False):
    """Generate release names for Montréal Python edition

    num: amount of names to generate
    names: list of English names in format "Adjective Noun"
    translate: query google translate to provide French translation

    returns a tuple of two lists in format: (french names, english names)
    """
    en_names = []
    fr_names = []

    for en_name in sorted(names, key=len):
        if len(en_names) == num:
            break

        if not translate:
            en_names.append(en_name)
            continue

        translator = Translator(from_lang='en', to_lang='fr')
        fr_name = translator.translate(en_name).encode('utf8')

        # allow another run when the translated name
        # produces more than two words for our release name
        if len(fr_name.split(' ')) != 2:
            continue

        en_adj, en_noun = en_name.strip().split(' ')
        fr_adj, fr_noun = fr_name.strip().split(' ')

        # only keep release names for which one of the
        # translation's opposed word is a match.
        s_fr_adj = strip_accents(fr_adj.decode('utf8'))
        s_fr_noun = strip_accents(fr_noun.decode('utf8'))

        save = lambda l, adj, noun: l.append(' '.join([adj, noun]))
        if s_fr_adj == en_noun:
            # TODO: s_fr_adj is really french?
            save(en_names, en_adj, en_noun)
            save(fr_names, fr_adj, fr_noun)
            continue
        elif s_fr_noun == en_adj:
            # TODO: s_fr_noun is really french?
            save(en_names, en_adj, en_noun)
            save(fr_names, fr_adj, fr_noun)
            continue
        elif show_excluded:
            c = lambda c: ' '.join([w.capitalize() for w in c.split(' ')])
            print("excluded: %s (%s)" % (c(en_name), c(fr_name)))

    return fr_names, en_names
开发者ID:mtlpy,项目名称:mtlpy-release,代码行数:54,代码来源:release.py

示例14: doTranslate

# 需要导入模块: from translate import Translator [as 别名]
# 或者: from translate.Translator import translate [as 别名]
    def doTranslate(self):
        openDirName = self.getOpenFileName()
        trans = Translator(to_lang="ko")
        trans.from_lang = self.lang_code[str(self.cb_fromLang.currentText())]
        self.label.setText("Under translating")
        for langCode in self.lang_code.keys():
            try:
                writeFile = open(openDirName+"\\"+langCode+"_"+self.originalFileName,'w')
                transResult=''
                trans.to_lang = self.lang_code[langCode]
                for line in self.readText:
                    try:
                        transResult += trans.translate(line).encode('utf-8')+"\n"
                    except:
                        transResult += trans.translate(line)+'\n'
                writeFile.write(transResult)
                writeFile.close()
            except:
                print langCode
                print self.readText
                break

        self.label.setText("Working done")
开发者ID:HeesangLee,项目名称:GoogleTranslate,代码行数:25,代码来源:GoogleTranslate.py

示例15: setTargetCountry

# 需要导入模块: from translate import Translator [as 别名]
# 或者: from translate.Translator import translate [as 别名]
    def setTargetCountry(self, targetcountrynames, language='es'):
        path = os.path.join(kmethods.__path__[0], 'new_country_db.json')
        translator = Translator(from_lang='en',to_lang='es')        
        
        hashtable = kgen.jload(path)
        
        targettable = dict()
        if(type(targetcountrynames)==list):            
            for n in targetcountrynames:
                try:
                    if(type(n)==unicode):
                        n = unicodedata.normalize('NFKD', n).encode('ascii','ignore').lower()
                    transn = translator.translate(n).lower()
                    targettable[n] = hashtable.pop(n)
                    if(hashtable.has_key(transn)):
                        targettable[transn] = hashtable.pop(transn)
                except:
                    print "name %s not found" % n
        elif(type(targetcountrynames)==str or type(targetcountrynames)==unicode):
            try:
                if(type(targetcountrynames)==unicode):
                    targetcountrynames = unicodedata.normalize('NFKD', targetcountrynames).encode('ascii','ignore').lower()
                transn = translator.translate(targetcountrynames).lower()
#                transn = u'm\u00e9xico'
                targettable[targetcountrynames] = hashtable.pop(targetcountrynames)
                if(hashtable.has_key(transn)):
                    targettable[transn] = hashtable.pop(transn)
            except:
                print "name %s not found" % targetcountrynames
        else:
            print "please input list or string"
            return
            
        allterms = [k for t in hashtable.values() for k in t.values()]
        self.NonTargetCountries = dict(zip(allterms, range(len(allterms))))
        alltargets = [k for t in targettable.values() for k in t.values()]
        self.TargetCountries = dict(zip(alltargets, range(len(alltargets))))
开发者ID:klyc0k,项目名称:EDSFilter,代码行数:39,代码来源:twitter_methods.py


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