简体   繁体   中英

Why does my python dictionary not updating properly?

Hello I am trying to store my words I translate using the google api so I don't have to do the same translation twice. So here is my code:

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

where transdicten-es.txt is a file containing translations written to it in the following format:

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

My trouble is that often words that have already been translated end up being translated again, not just retrieved from the dictionary and I cannot work out why! If it helps, translate() is being called many 1000s of times in a row in a for loop. Thanks.

Your bare except clauses will hide each and any exception, so you just don't now what really happens in your code. As a rule of thumb: never use bare except clauses, only catch the exceptions you expect AND can handle - or at least log exceptions one way or another and never do anything potentially harmful assuming you know what happened when you don't. In your case, loadtransdict should not create an empty file, but it should definitly mention something went wrong:

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

This might not solve the root cause by itself but you should had least get a clue about what went wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM