import xml.sax
from xml.sax.handler import ContentHandler
import sys

class SALDOHandler(ContentHandler):
    def __init__(self, sk2ss):
        self.saldoSense = ""
        self.synset = ""
        self.sk2ss = sk2ss

    def startElement(self, name, attrs):
        if name == "Sense":
            self.saldoSense = ""
            self.synset = ""
        elif name == "feat":
            if attrs["att"] == "saldoSense":
                self.saldoSense = attrs["val"]
            elif attrs["att"] == "synset":
                self.synset = attrs["val"]

            if self.saldoSense and self.synset:
                if self.synset in self.sk2ss:
                    print("%s\tswe:lemma\t%s" % (self.sk2ss[self.synset], self.saldoSense[:self.saldoSense.index("..")].replace("_"," ")))
                else:
                    sys.stderr.write("lost key %s\n" % self.synset)
                self.saldoSense = ""
                self.synset = ""

def main():
    senseKey2Synset = dict()
    # senses is generated by:
    #    python senses-from.dump.py /path/to/wordnet/
    for line in open("senses"):
        synsetid, sensekey = line.strip().split(" ")
        senseKey2Synset[sensekey] = synsetid
    print("# SALDO\tswe\thttp://spraakbanken.gu.se/eng/resource/wordnet-saldo\tCC-BY 3.0")
    xml.sax.parse(open("wordnet-saldo.xml"),SALDOHandler(senseKey2Synset))

if __name__ == "__main__":
    main()




