机器翻译

# -*- coding:utf-8 -*-
import json

class Translate:
    def __init__(self,dict_file):
        d = dict()
        for line in file(dict_file):
            line = unicode(line, "utf8")
            t = line.strip().split(" ", 2)
            t.append(u'')
            if d.get(t[0]) is None:
                d[t[0]] = {t[1]: t[2]}
            else:
                d[t[0]][t[1]] = t[2]
        self.dictionary = d

    def translate(self,src_file):
        js = json.load(file(src_file))
        return json.dumps(self.parse_json("", js), indent=4)

    def get_target(self,key, path):
        d = self.dictionary.get(key)
        if d is None:
            return key
        t = d.get(path)
        if t == "":
            return key
        elif t is None:
            return d.get("/")
        else:
            return t

    def parse_json(self,p, dic_json):
        if isinstance(dic_json, dict):
            d = dict()
            for key in dic_json:
                if isinstance(dic_json[key], dict) or isinstance(dic_json[key], list):
                    # print("%s/%s : %s" % (p, key, dic_json[key]))
                    d[key] = self.parse_json(p + "/" + key, dic_json[key])
                else:
                    # print("%s/%s : %s" % (p, key, dic_json[key]))
                    v = self.get_target(dic_json[key], "%s/%s" % (p, key))
                    d[key] = v
            return d
        elif isinstance(dic_json, list):
            l = []
            for t in dic_json:
                if isinstance(t, dict):
                    l.append(self.parse_json(p, t))
                else:
                    v = self.get_target(t, p)
                    l.append(v)
                    # print("%s : %s" % (p, t))
            return l


def main():
    translator = Translate("dictionary.txt")
    print translator.translate("example.json")


if __name__ == '__main__':
    main()

字典数据(dictionary.txt)

父母 /name parents
老大 /child/name big brother
老大 /grandson/name big grandson
老二 / little brother
老二 /grandson/name

翻译源文件(exmaple.json)

{
  "name":"父母",
  "type":1,
  "child":[
    {"name":"老大"},
    {"name":"老二"}
  ],
  "grandson":[
    {"name":"老大"},
    {"name":"老二"}
  ]
}

 

posted on 2018-01-30 23:39  学而知之者  阅读(105)  评论(0编辑  收藏  举报