有没有用Python编写的GEDCOM解析器?

2024-05-23 22:04:38 发布

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

GEDCOM是一个交换系谱数据的标准。在

我找到了用

但到目前为止还没有一个是用Python编写的。最接近我的是来自GRAMPS项目的文件libgedcom.py,但是它充满了对GRAMPS模块的引用,以至于我无法使用它。在

我只想要一个简单的用Python编写的独立GEDCOM解析器库。这个存在吗?在


Tags: 模块文件数据项目py解析器标准perl
3条回答

我从mwhite的答案中提取了代码,对其进行了一点扩展(好的,不仅仅是一点点),并发布在github:http://github.com/dijxtra/simplepyged。我采纳了关于其他补充内容的建议:-)

几年前,作为larger project的一部分,我用Python编写了一个简单的GEDCOM-to-XML转换器。我发现以XML格式处理GEDCOM数据要容易得多(特别是下一步涉及XSLT时)。在

我现在还没有在线代码,所以我已经将模块粘贴到这条消息中。这对我有效;没有保证。希望这有帮助。在

import codecs, os, re, sys
from xml.sax.saxutils import escape

fn = sys.argv[1]

ged = codecs.open(fn, encoding="cp437")
xml = codecs.open(fn+".xml", "w", "utf8")
xml.write("""<?xml version="1.0"?>\n""")
xml.write("<gedcom>")
sub = []
for s in ged:
    s = s.strip()
    m = re.match(r"(\d+) (@(\w+)@ )?(\w+)( (.*))?", s)
    if m is None:
        print "Error: unmatched line:", s
    level = int(m.group(1))
    id = m.group(3)
    tag = m.group(4)
    data = m.group(6)
    while len(sub) > level:
        xml.write("</%s>\n" % (sub[-1]))
        sub.pop()
    if level != len(sub):
        print "Error: unexpected level:", s
    sub += [tag]
    if id is not None:
        xml.write("<%s id=\"%s\">" % (tag, id))
    else:
        xml.write("<%s>" % (tag))
    if data is not None:
        m = re.match(r"@(\w+)@", data)
        if m:
            xml.write(m.group(1))
        elif tag == "NAME":
            m = re.match(r"(.*?)/(.*?)/$", data)
            if m:
                xml.write("<forename>%s</forename><surname>%s</surname>" % (escape(m.group(1).strip()), escape(m.group(2))))
            else:
                xml.write(escape(data))
        elif tag == "DATE":
            m = re.match(r"(((\d+)?\s+)?(\w+)?\s+)?(\d{3,})", data)
            if m:
                if m.group(3) is not None:
                    xml.write("<day>%s</day><month>%s</month><year>%s</year>" % (m.group(3), m.group(4), m.group(5)))
                elif m.group(4) is not None:
                    xml.write("<month>%s</month><year>%s</year>" % (m.group(4), m.group(5)))
                else:
                    xml.write("<year>%s</year>" % m.group(5))
            else:
                xml.write(escape(data))
        else:
            xml.write(escape(data))
while len(sub) > 0:
    xml.write("</%s>" % sub[-1])
    sub.pop()
xml.write("</gedcom>\n")
ged.close()
xml.close()

我知道这个线程很旧,但我在我的搜索和这个项目中找到了它https://github.com/madprime/python-gedcom/

源是安静干净和非常功能。在

相关问题 更多 >