GEDCOM是交换家谱数据的标准。
我发现解析器是用
但到目前为止还没有用Python编写的代码。与我最接近的是来自GRAMPS项目的文件libgedcom.py,但它充满了对GRAMPS模块的引用,对我来说不是很有用。
我只想要一个用Python编写的简单独立的GEDCOM解析库。这真的存在吗?
发布于 2010-01-26 07:55:15
几年前,我用Python语言编写了一个简单的GEDCOM to 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()
发布于 2010-10-19 00:54:33
我从github的答案中提取了代码,对其进行了一点扩展(好吧,不仅仅是一点),并发布在github:http://github.com/dijxtra/simplepyged上。我接受关于添加其他内容的建议:-)
发布于 2014-12-19 07:49:34
我知道这个帖子很老了,但是我在搜索和这个项目https://github.com/madprime/python-gedcom/中找到了它
源码非常干净,功能也非常强大。
https://stackoverflow.com/questions/1919593
复制相似问题