您好,我正在尝试存储我使用 google api 翻译的单词,因此我不必两次进行相同的翻译。所以这是我的代码:
def loadtransdict(fro, to):
try:
tdictf = open("transdict"+fro+"-"+to+".txt", "r")
pairs = tdictf.read().split(",")
tdictf.close()
tdict = {}
for pair in pairs:
tdict[pair.split(":")[0]] = pair.split(":")[1]
return tdict
except:
tdictf = open("transdict"+fro+"-"+to+".txt", "w")
tdictf.close()
return {}
else:
return None
def writetodict(fro, to, sword, dword):
try:
tdictf = open("transdict"+fro+"-"+to+".txt", "r")
if tdictf.read() == "":
tdictf = open("transdict"+fro+"-"+to+".txt", "a")
tdictf.write(sword+":"+dword)
else:
tdictf = open("transdict"+fro+"-"+to+".txt", "a")
tdictf.write(","+sword+":"+dword)
tdictf.close()
except:
return None
def translate(original_word, fro, to):
tdict = loadtransdict(fro, to)
if original_word in tdict:
return tdict[original_word]
else:
print original_word
print tdict
#mm = requests.get('http://api.mymemory.translated.net/get?q='+word+'&langpair='+fro+'|'+to)
gt = requests.get('https://www.googleapis.com/language/translate/v2?key=MYKEY='\
+original_word+'&source='+fro+'&target='+to+'&prettyprint=false')
translated_word = re.search("translatedText\":\"(.*)\"", gt.text).group(1)
writetodict(fro,to,original_word,translated_word)
return translated_word
其中 transdicten-es.txt 是一个文件,其中包含以下列格式写入的翻译:
经常:constantemente,命令:ordenado,潮湿:humedad,错误:模棱两可,尊严:dignidad
我的问题是,通常已经翻译的单词最终会被再次翻译,而不仅仅是从字典中检索到,我无法弄清楚为什么!如果有帮助,则 translate() 在 for 循环中连续被调用 1000 次。谢谢。