使用Python GEDCOM解析器:输出不正确(gedcom.Element实例在0x00...)

0 投票
2 回答
703 浏览
提问于 2025-04-16 03:36

我刚开始学Python,跟你们比起来,我的编程经验几乎可以忽略不计。大家准备好了吗 :)

我有两个文件。一个是用Python写的GEDCOM解析器,我是在这个网站上找到的(gedcom.py - http://ilab.cs.byu.edu/cs460/2006w/assignments/program1.html),另一个是我从heiner-eichmann.de/gedcom/gedcom.htm上下载的简单GEDCOM文件。你们猜猜谁在把这两个东西结合起来时遇到麻烦?就是我...

下面是我写的一小段代码,还有我到目前为止做的事情。

class Gedcom:
""" Gedcom parser

This parser is for the Gedcom 5.5 format.  For documentation of
this format, see

http://homepages.rootsweb.com/~pmcbride/gedcom/55gctoc.htm

This parser reads a GEDCOM file and parses it into a set of
elements.  These elements can be accessed via a list (the order of
the list is the same as the order of the elements in the GEDCOM
file), or a dictionary (the key to the dictionary is a unique
identifier that one element can use to point to another element).

"""

def __init__(self,file):
    """ Initialize a Gedcom parser. You must supply a Gedcom file.
    """
    self.__element_list = []
    self.__element_dict = {}
    self.__element_top = Element(-1,"","TOP","",self.__element_dict)
    self.__current_level = -1
    self.__current_element = self.__element_top
    self.__individuals = 0
    self.__parse(file)

def element_list(self):
    """ Return a list of all the elements in the Gedcom file.  The
    elements are in the same order as they appeared in the file.
    """
    return self.__element_list

def element_dict(self):
    """ Return a dictionary of elements from the Gedcom file.  Only
    elements identified by a pointer are listed in the dictionary.  The
    key for the dictionary is the pointer.
    """
    return self.__element_dict

我写的小脚本

import gedcom
g = Gedcom('C:\tmp\test.ged') //我在用Windows
print g.element_list()

从这里,我得到了很多输出,比如“gedcom.Element instance at 0x00...”

我不明白为什么会得到这样的输出。我以为根据element_list方法应该会返回一个格式化的列表。我在网上搜索过,也在这个网站上查找过。答案可能就在我面前,但我希望有人能指出来。

非常感谢。

2 个回答

0

这个输出结果没有什么问题,也不算奇怪。因为 gedcom.Element 这个类没有定义 __repr__ 方法,所以打印这个列表的时候就会显示默认的 __repr__。如果你想访问每个元素的某个特定属性,可以试试下面的方法:

print [element.some_attribute for element in g.element_list()]

补充:哦,我看了你提供的源代码。确实定义了 __str__ 方法,但没有 __repr__。你可能想要的就是这个:

for element in g.element_list()
    print element
1

someclass instance at 0xdeadbeef 是一种标准的输出方式,表示一个类的实例,但这个类没有定义自己的输出格式。看起来 gedcom.Element 这个类就是没有定义,所以你在打印一系列这样的实例时就会看到这个结果。如果这个类定义了 __str__ 方法,你可以

for x in g.element_list():
    print x

但是如果没有定义 __str__ 方法,那么输出结果也会类似(因为 __str__ 默认会使用 __repr__ 的输出)。你想要对这些元素做什么呢?比如说,看看这个类提供了什么方法?

撰写回答