使用 Python GEDCOM 解析器:接收到错误的输出(gedcom.Element 实例位于 0x00…)

StackOverflow https://stackoverflow.com/questions/3623349

  •  26-09-2019
  •  | 
  •  

我是 Python 新手,我可以立即说,与你们中的许多人相比,我的编程经验是微不足道的。振作起来:)

我有2个文件。我从本网站的用户那里找到了一个用 Python 编写的 GEDCOM 解析器(gedcom.py - http://ilab.cs.byu.edu/cs460/2006w/assignments/program1.html)和一个我从 heiner-eichmann.de/gedcom/gedcom.htm 中提取的简单 GEDCOM 文件。猜猜谁在将 2 和 2 放在一起时遇到困难?这家伙...

这是一个代码片段,后面是我迄今为止所做的事情。

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

我的小脚本

导入 gedcom
g = Gedcom('C: mp est.ged') //我在 Windows 上
打印 g.element_list()

从这里,我收到一堆输出“gedcom.Element instance at 0x00...”

我不确定为什么会收到此输出。我认为根据 element_list 方法将返回一个格式化列表。我用谷歌搜索并搜索了这个网站。答案可能就在我面前,但我希望有人能指出显而易见的事情。

非常感激。

有帮助吗?

解决方案

someclass instance at 0xdeadbeef 是标准的结果 __repr__ 未定义类的方法,显然是类 gedcom.Element 没有,所以问题仅在于您打印此类实例的列表。如果这样的类定义 __str__, , 你可以

for x in g.element_list():
    print x

但如果没有,也会给出类似的输出(如 __str__ “默认为” __repr__)。你想做什么 与这些元素,例如他们的班级的方法 提供?

其他提示

该输出没有任何错误或异常。因为 gedcom.Element 还没有定义一个 __repr__, ,打印列表会显示默认值 __repr__. 。如果您想访问每个元素的特定属性,您可以尝试:

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

编辑: 啊哈,我看了你提供的来源。它确实定义了一个 __str__, , 但不是 __repr__. 。这很可能是您想要的:

for element in g.element_list()
    print element
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top