【问题标题】:Some element.tail attributes are empty although they shouldn't一些 element.tail 属性是空的,尽管它们不应该
【发布时间】:2016-08-18 21:13:12
【问题描述】:

我正在尝试使用 python 3.4 中的 xml.etree.ElementTree 解析 large XML file (带有一本圣经书)(为了与 Windows 兼容,我更愿意使用标准库模块),相关方法在这里.

class BibleTree:
    def __init__(self, file_name: str) -> None:
        self.root = ET.parse(file_name).getroot()

    @staticmethod
    def _list_to_clean_text(str_in: str) -> str:
        out = re.sub(r'[\s\n]+', ' ', str_in, flags=re.DOTALL)
        return out.strip()

    @staticmethod
    def _clean_text(intext: Optional[str]) -> str:
        return intext if intext is not None else ''

    def __iter__(self) -> Tuple[int, int, str]:
        collected = None
        cur_chap = 0
        cur_verse = 0

        for child in self.root:
            if child.tag in ['kap', 'vers']:
                if collected and collected.strip():
                    yield cur_chap, cur_verse, self._list_to_clean_text(collected)
                if child.tag == 'kap':
                    cur_chap = int(child.attrib['n'])
                elif child.tag == 'vers':
                    cur_verse = int(child.attrib['n'])
                collected = self._clean_text(child.tail)
            else:
                if collected is not None:
                    collected += self._clean_text(child.text)
                    collected += self._clean_text(child.tail)

问题在于,在某些情况下(例如,第 54 行的元素 <odkazo/>),变量 childtail 属性为 None,尽管恕我直言,它应该是文本。

有什么想法,请问我做错了什么?

【问题讨论】:

  • 代码到底应该做什么?代码不完整,无法运行;例如有一个对Optional 的引用,它没有被定义。如果您能提供一个明确的minimal reproducible example,这将有所帮助。

标签: python xml elementtree


【解决方案1】:

这是 PEBKAC ... 我假设其他元素中没有里程碑元素。所以,我需要将整个函数重写为递归函数。哦,好吧。

【讨论】:

    猜你喜欢
    • 2018-02-09
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    相关资源
    最近更新 更多