您好我正在尝试存储我使用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,错误:equivocado,尊严:dignidad
我的麻烦是,经常被翻译的单词最终会被翻译,而不仅仅是从字典中检索出来,我无法理解为什么!如果有帮助,则在for循环中连续多次调用translate()1000次。感谢。
答案 0 :(得分:0)
你的bare except子句会隐藏每个和任何异常,所以你现在不知道代码中真正发生了什么。根据经验:从不使用bare except子句,只捕获您期望和可以处理的异常 - 或者至少以某种方式记录异常,并且永远不会做任何可能有害的事情,假设您知道发生了什么你没有。在你的情况下,loadtransdict
不应该创建一个空文件,但它应该明确提到出错了:
def loadtransdict(fro, to):
tdict = {}
filename = "transdict"+fro+"-"+to+".txt"
try:
tdictf = open(filename, , "r")
data = tdictf.read()
tdictf.close()
except Exception, e:
print "failed to open '%s'for reading : %s" % (filename, e)
else:
pairs = data.split(",")
for pair in pairs:
tdict[pair.split(":")[0]] = pair.split(":")[1]
return tdict
def writetodict(fro, to, sword, dword):
filename = "transdict"+fro+"-"+to+".txt"
try:
tdictf = open(filename, "rw")
except Exception, e:
print "failed to open '%s'for read/write : %s" % (filename, e)
return False
data = tdictf.read().strip()
sep = "," if data else ""
tdictf.write(data + sep + sword + ":" + dword)
tdictf.close()
return True
这可能无法自行解决根本原因,但你应该最不清楚哪里出了问题。