为什么我的python字典没有正确更新?

2024-09-27 22:19:36 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我试图存储我的话,我翻译使用谷歌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文件是一个包含以下格式的翻译的文件:

constantly:constantemente,commanded:ordenado,damp:humedad,mistaken:equivocado,dignity:dignidad

我的问题是,很多已经被翻译过的单词最终会被再次翻译,而不仅仅是从字典中检索到,我也不知道为什么!如果有帮助的话,translate()在for循环的一行中被多次调用。谢谢。你知道吗


Tags: totxtclosereturndefopenwordsplit
1条回答
网友
1楼 · 发布于 2024-09-27 22:19:36

裸露的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

这可能无法解决根本原因本身,但你至少应该得到一个线索是什么出了问题。你知道吗

相关问题 更多 >

    热门问题