[英]Why does my python dictionary not updating properly?
您好,我正在尝试存储我使用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()千次。 谢谢。
您的单独的except子句将隐藏每个异常,因此您现在不了解代码中实际发生的情况。 根据经验: 永远不要使用裸子句,仅捕获您期望并可以处理的异常-或至少以一种或另一种方式记录异常,并且假设您知道不知道会发生什么,则不要做任何可能有害的事情。 在您的情况下, loadtransdict
不应创建一个空文件,但应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
这可能无法单独解决根本原因,但您应该至少了解出了什么问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.