0

您好,我正在尝试存储我使用 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 次。谢谢。

4

1 回答 1

0

您裸露的 except 子句将隐藏每个异常,因此您现在不知道代码中真正发生了什么。作为一个经验法则:永远不要使用裸的 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

这本身可能无法解决根本原因,但您至少应该知道出了什么问题。

于 2013-04-10T15:08:12.477 回答