是否有用Python编写的GEDCOM解析器?

时间:2009-12-17 05:11:00

标签: python parsing genealogy gedcom

GEDCOM是交换家谱数据的标准。

我发现用

编写的解析器

但到目前为止还没有用Python编写。我最接近的是来自GRAMPS项目的文件libgedcom.py,但是对GRAMPS模块的引用如此之多,以至于我无法使用。

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

6 个答案:

答案 0 :(得分:8)

几年前,我在Python中编写了一个简单的GEDCOM到XML转换器,作为larger project的一部分。我发现以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()

答案 1 :(得分:7)

我从mwhite的答案中获取了代码,将其扩展了一点(好的,不仅仅是一点点)并发布在github:http://github.com/dijxtra/simplepyged。我会提出有关添加其他内容的建议: - )

答案 2 :(得分:4)

我知道这个帖子很老了,但我在搜索和项目https://github.com/madprime/python-gedcom/

中找到了它

源头很干净,非常实用。

答案 3 :(得分:2)

Python中的通用GEDCOM解析器是从http://ilab.cs.byu.edu/cs460/2006w/assignments/program1.html

链接的

答案 4 :(得分:1)

您可以使用SWIG工具通过本机语言界面包含C库。您必须在Python中对C api进行调用,但其余代码只能是Python。

可能听起来有点令人生畏,但是一旦你设置了东西,将两者结合使用也不会太糟糕。根据C库的编写方式可能存在一些怪癖,但无论您使用哪种选项,都必须处理一些。

答案 5 :(得分:0)

GEDCOM 5.5格式的另一个基本解析器:https://github.com/rootsdev/python-gedcom-parser