本文整理汇总了Python中translate.translate函数的典型用法代码示例。如果您正苦于以下问题:Python translate函数的具体用法?Python translate怎么用?Python translate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了translate函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: main
def main():
rules = loadrules("pokemon.yaml")
trees = []
trees.append(Tree("(S let me show you my Pokémon)"))
trees.append(Tree("(S let me show you my cats)"))
for tree in trees:
translate(tree, rules)
开发者ID:OMARI1988,项目名称:kurt,代码行数:8,代码来源:pokemon.py
示例2: makeMutantFromSequence
def makeMutantFromSequence(target_protein_seq, base_dna_seq):
codons = [x for x in translate.codons(base_dna_seq)]
base_prot_seq = translate.translate(base_dna_seq)
assert len(base_prot_seq) == len(target_protein_seq)
mutant_dna_seq = ''
for (i, aa) in enumerate(target_protein_seq):
if aa == base_prot_seq[i]:
mutant_dna_seq += codons[i]
else:
mutant_dna_seq += translate.randomReverseTranslate(aa)
assert translate.translate(mutant_dna_seq) == target_protein_seq
return mutant_dna_seq
开发者ID:dad,项目名称:lcscore,代码行数:12,代码来源:proteins-to-genes.py
示例3: main
def main():
rules = loadrules("german.yaml")
trees = []
## I like eating / Ich esse gern
trees.append(Tree("(S (NP (PRP I)) (VP (VB like) (VBG eating)))"))
## I am hungry / Ich habe Hunger
trees.append(Tree("(S (NP (PRP I)) (VP (VB am) (JJ hungry)))"))
for tree in trees:
translate(tree, rules)
开发者ID:alexrudnick,项目名称:kurt,代码行数:12,代码来源:german.py
示例4: test_ende
def test_ende(self):
with open('en-de/in', 'r', encoding='utf-8') as in_file, \
open('en-de/out', 'w', encoding='utf-8') as out_file:
os.chdir('models/en-de/')
settings = TranslationSettings()
settings.input = in_file
settings.output = out_file
settings.models = ["model.npz"]
settings.beam_size = 12
settings.normalization_alpha = 1.0
translate(settings=settings)
os.chdir('../..')
self.outputEqual('en-de/ref2','en-de/out')
开发者ID:rsennrich,项目名称:nematus,代码行数:13,代码来源:test_translate.py
示例5: process
def process(msg):
if msg.startswith('#') or msg.startswith('#'):
pass
elif msg == u'新生指南':
return freshman.get_guidance(), "news"
elif msg == u'新闻' or msg == u'体育' or msg == u'体育新闻':
return news.getNews(msg), "news"
elif isinstance(msg, type('string')):
msg = msg.lower()
msg = msg.strip()
if msg == 'bbc world' or msg == 'bbc china' or msg == 'bbc' or msg == 'nba':
return news.getNews(msg), "news"
else:
return translate.translate(msg), "text"
#elif msg == u'新闻':
# return news_info, "text"
elif msg == u'校车' or msg == u'明天校车':
return xiaoche.get_timetable(msg), "text"
elif msg == u'摆渡车':
return ferrybus.get_timetable(msg), "text"
elif msg == u'环一' or msg == u'环1':
return huanyi.get_timetable(), "text"
elif msg == u'天气':
return weather.weather(), "text"
elif msg == u'空气':
return weather.get_airquality(), "text"
elif re.match(u"发状态", msg):
if msg[3:]:
return renren.renren_status(msg[3:]), "text"
else:
return u"请输入状态内容", "text"
else:
return u"无法处理请求,请查看使用说明\n" + help_info + report_info, "text"
开发者ID:zhangyan001,项目名称:bit,代码行数:33,代码来源:views.py
示例6: createAlgsList
def createAlgsList(self):
# First we populate the list of algorithms with those created
# extending GeoAlgorithm directly (those that execute GDAL
# using the console)
self.preloadedAlgs = [nearblack(), information(), warp(), translate(),
rgb2pct(), pct2rgb(), merge(), buildvrt(), polygonize(), gdaladdo(),
ClipByExtent(), ClipByMask(), contour(), rasterize(), proximity(),
sieve(), fillnodata(), ExtractProjection(), gdal2xyz(),
hillshade(), slope(), aspect(), tri(), tpi(), roughness(),
ColorRelief(), GridInvDist(), GridAverage(), GridNearest(),
GridDataMetrics(), gdaltindex(), gdalcalc(), rasterize_over(),
# ----- OGR tools -----
OgrInfo(), Ogr2Ogr(), Ogr2OgrClip(), Ogr2OgrClipExtent(),
Ogr2OgrToPostGis(), Ogr2OgrToPostGisList(), Ogr2OgrPointsOnLines(),
Ogr2OgrBuffer(), Ogr2OgrDissolve(), Ogr2OgrOneSideBuffer(),
Ogr2OgrTableToPostGisList(), OgrSql(),
]
# And then we add those that are created as python scripts
folder = self.scriptsFolder()
if os.path.exists(folder):
for descriptionFile in os.listdir(folder):
if descriptionFile.endswith('py'):
try:
fullpath = os.path.join(self.scriptsFolder(),
descriptionFile)
alg = GdalScriptAlgorithm(fullpath)
self.preloadedAlgs.append(alg)
except WrongScriptException as e:
ProcessingLog.addToLog(ProcessingLog.LOG_ERROR, e.msg)
开发者ID:Geoneer,项目名称:QGIS,代码行数:30,代码来源:GdalOgrAlgorithmProvider.py
示例7: shindan
def shindan(bot, trigger):
"""
.shindan <id> [name] - Do the shindanmaker thing! Will automatically translate japanese shindans to english. (Waifu id: 215100 | Teh_Colt's Drama Gen id: 490953)
"""
if not trigger.group(3) or not trigger.group(3).isdigit() or int(trigger.group(3).strip()) < 2000:
bot.say('You must specify a shindanmaker ID (Waifu id: 215100 | Teh_Colt\'s Drama Gen id: 490953)')
return
name = trigger.nick
if (trigger.group(4)):
name = trigger.group(4)
data = web.urlencode({'u': name, 'from': ''}).encode('ascii')
url = follow_redirects('http://en.shindanmaker.com/'+trigger.group(3).strip())
try:
soup = get_soup(web.post(url, data))
shindan = soup.find(attrs={'class':re.compile("result")})
if 'en' in url:
bot.say(shindan.text.strip())
else:
msg, in_lang = translate.translate(shindan.text.strip())
if in_lang == 'ja':
in_lang = 'Japanese'
bot.say('%s (Translated from %s)' % (msg, in_lang))
except Exception as e:
bot.say('418 I\'m a teapot')
开发者ID:meew0,项目名称:inumuta-modules,代码行数:25,代码来源:shindan.py
示例8: main
def main(connection, info, args):
"""Translates using google translate"""
connection.msg(
info["channel"],
'%s: "%s"'
% (info["sender"], partfilter(translate.translate(args[1], args[2], " ".join(args[3:])).encode("utf-8"))),
)
开发者ID:sonicrules1234,项目名称:sonicbot,代码行数:7,代码来源:gtranslate.py
示例9: process_translate
def process_translate(i, words):
from_language = "en"
into_language = "en"
for j,graph in enumerate(words):
if graph == "from":
from_language = words[j+1]
if graph =="into":
into_language = words[j+1]
if from_language in rev_lang_dict and into_language in rev_lang_dict:
espeak("translate from " + from_language + " into " + into_language)
espeak("say the phrase: ")
hypos = continuous_listen.listen(from_language)
if len(hypos) > 0 and type(hypos) is not str:
confidence, speech = hypos[0]['confidence'], str(hypos[0]['utterance'])
espeak("translating ")
espeak(speech, language_dict[from_language])
espeak("into " + into_language)
translation = translate.translate(sentence, language_dict[into_language])
espeak(translation, language_dict[into_language])
else:
espeak("input not understood")
else:
espeak("language is not supported")
开发者ID:adamreis,项目名称:pivision,代码行数:25,代码来源:runner.py
示例10: main
def main():
"""
Stages
1. Setup stuff from arguments
2. Ignore certain lines of code.
3. Add necessary includes and main function.
4. Actual translation.
"""
args = get_args()
if not error_check_python(args.file):
return 1
elif args.ast_tree:
translate.prettyparseprintfile(args.file)
return 0
translated_code = translate.translate(
args.file, indent_size=args.indent_size)
if args.compile_check:
return 0 if error_check_c(translated_code) else 2
elif args.execute:
return 0 if error_check_c(translated_code, True) else 2
elif args.memory_check:
return memory_check(translated_code)
else:
print(translated_code)
return 0
开发者ID:PiJoules,项目名称:python2c,代码行数:29,代码来源:python2c.py
示例11: run
def run(args):
if args.input_file:
with open(args.input_file, "r") as input_file:
source = input_file.read()
else:
import sys
source = sys.stdin.read()
if args.assemble:
with open(args.output, "w") as binout:
write_binary(parse_instructions(source), binout)
else:
tree = parse(preprocess(source))
if args.print_ast:
print_tree(tree)
if not tree:
return
instructions = link(*translate(tree))
if args.print_assembly:
print_instructions(instructions)
with open(args.output, "w") as binout:
write_binary(instructions, binout)
开发者ID:haldean,项目名称:cvm,代码行数:25,代码来源:cvm.py
示例12: translateExamples
def translateExamples(inputDir, outputDir, targetsDir, includedTargets=None):
# Load all target dictionaries
targets = []
for target in os.listdir(targetsDir):
# Ignore targets not in includedTargets
if includedTargets and not os.path.basename(target).split(".")[0] in includedTargets:
continue
with open(os.path.join(targetsDir, target)) as tFile:
targets.append(json.load(tFile))
# Translate each example
for f in os.listdir(inputDir):
# Ignore hidden files
if f[0] == ".":
continue
# Parse the example file
with open(os.path.join(inputDir,f), 'r') as file:
ast = parse(file.read(), f)
basename = f[:-len(".sg")]
# Translate ast to each target language
for target in targets:
translation = translate(ast, targetDict=target)
directory = os.path.join(outputDir, target["OutputDirectoryName"])
extension = target["FileExtension"]
# Create directory if it does not exist
if not os.path.exists(directory):
os.makedirs(directory)
# Write translation
with open(os.path.join(directory, basename + extension), "w") as nf:
nf.write(translation)
开发者ID:42MachineLearning,项目名称:shogun,代码行数:35,代码来源:generate.py
示例13: detectPrintMessage
def detectPrintMessage(pktlen, data, timestamp):
# Magical numbers and structure taken from original Dota 2 Translator
if not data:
return
if data[12:14]=='\x08\x00':
decoded = decode_ip_packet(data[14:])
data = decoded['data']
identifierLength = len(ALL_CHAT_IDENTIFIER) + 2
chatFound = str.find(data, ALL_CHAT_IDENTIFIER)
type = 0
# If no all chat found
if (chatFound == -1):
identifierLength = len(TEAM_CHAT_IDENTIFIER) + 2
chatFound = str.find(data, TEAM_CHAT_IDENTIFIER)
type = 1
# If either all or team chat message found
if (chatFound != -1):
indexName = chatFound + identifierLength
lengthName = ord(data[indexName - 1]) # Get the ascii-value
indexMessage = indexName + lengthName + 2
lengthMessage = ord(data[indexMessage - 1]) # Get the ascii-value
name = data[indexName:indexName+lengthName]
message = data[indexMessage:indexMessage+lengthMessage]
# "Terneray operator"~ish
print "[Allies] " if (type==1) else "", name, ": ", message, " => ", translate.translate(message)
开发者ID:Gasparen,项目名称:Dota2TranslatorLinux,代码行数:31,代码来源:sniff.py
示例14: test004
def test004(self):
"""translation with problems"""
s = "ATGCatTCTNNNTAAAGA"
# print translate.translate(s)
self.assertTrue(translate.translate(s) is None)
# print translate.translateRaw(s,bad_aa='@')
self.assertTrue(translate.translateRaw(s, bad_aa="@") == "[email protected]*R")
开发者ID:dad,项目名称:base,代码行数:7,代码来源:translate_test.py
示例15: test008
def test008(self):
"""zero-length nucleotides"""
s = ""
c = [cod for cod in translate.codons(s)]
self.assertTrue(len(c) == 0)
self.assertTrue(translate.translate(s) == "")
self.assertTrue(translate.translateRaw(s) == "")
开发者ID:dad,项目名称:base,代码行数:7,代码来源:translate_test.py
示例16: verifyWeak
def verifyWeak():
for (eng, ita) in StrongVerificationCases:
for e in eng:
translation = translate("Eng", "Ita", e)
if (not list_subset(translation, ita)):
print "Source: %s" % e
print "Expected: %s" % ita
print "Actual: %s" % translation
raise AssertionError ("Failed test case")
for i in ita:
translation = translate("Ita", "Eng", i)
if (not list_subset(translation, eng)):
print "Source: %s" % i
print "Expected: %s" % eng
print "Actual: %s" % translation
raise AssertionError ("Failed test case")
开发者ID:ethantkoenig,项目名称:Translation,代码行数:17,代码来源:verify.py
示例17: test009
def test009(self):
"""odd-length coding sequence"""
s = "TCTCGTAAGTACGCAGC"
c = [cod for cod in translate.codons(s)]
self.assertTrue(len(c) == 5)
self.assertTrue(c[-1] == "GCA")
self.assertTrue(translate.translate(s) is None)
self.assertTrue(translate.translateRaw(s) == "SRKYA")
开发者ID:dad,项目名称:base,代码行数:8,代码来源:translate_test.py
示例18: y_translate
def y_translate(text, langc="zh-CN"):
# http://api.yandex.com/translate/
from yandex_translate import YandexTranslate
translate = YandexTranslate('Your API key here.')
## print('Languages:', translate.langs)
## print('Translate directions:', translate.directions)
## print('Detect language:', translate.detect('Привет, мир!'))
## print('Translate:', translate.translate('Привет, мир!', 'ru-en'))
return translate.translate(text, langc)
开发者ID:hanteng,项目名称:pyBaidu,代码行数:9,代码来源:test_with_translation.py
示例19: test001
def test001(self):
"""reverse translate"""
N = 1000
aas = "ACDEFGHIKLMNPQRSTVWY"
for i in range(N):
prot = "".join([random.choice(aas) for xi in range(100)])
gene = translate.reverseTranslate(prot)
newprot = translate.translate(gene)
self.assertTrue(prot == newprot)
开发者ID:dad,项目名称:base,代码行数:9,代码来源:translate_test.py
示例20: construct_language
def construct_language(language):
print('Getting words')
foreign_words = get_words(language)
print('Translating words')
translate_dict = translate(foreign_words, language)
print('Getting English synonyms')
full_dict = construct_synonyms(translate_dict)
print('Saving language')
save_as_text_file(full_dict, language)
return full_dict
开发者ID:runnersaw,项目名称:language-learning,代码行数:10,代码来源:language_creator.py
注:本文中的translate.translate函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论