【发布时间】: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/>),变量 child 的 tail 属性为 None,尽管恕我直言,它应该是文本。
有什么想法,请问我做错了什么?
【问题讨论】:
-
代码到底应该做什么?代码不完整,无法运行;例如有一个对
Optional的引用,它没有被定义。如果您能提供一个明确的minimal reproducible example,这将有所帮助。
标签: python xml elementtree