【发布时间】:2020-01-09 11:47:24
【问题描述】:
我有一些通过 NLP 处理器运行的 XML。我必须在 Python 脚本中修改输出,所以对我来说没有 XSLT。我试图从我的 XML 中提取 <TXT> 和 </TXT> 中的所有原始文本作为字符串,但我一直坚持如何从 ElementTree 中提取它。
到目前为止我的代码是
import xml.etree.ElementTree as ET
xml_doc = """<?xml version="1.0" encoding="UTF-8"?>
<NORMDOC>
<DOC>
<DOCID>112233</DOCID>
<TXT>
<S sid="112233-SENT-001"><ENAMEX type="PERSON" id="PER-112233-001">George Washington</ENAMEX> and <ENAMEX type="PERSON" id="PER-112233-002">Thomas Jefferson</ENAMEX> were both founding fathers.</S>
<S sid="112233-SENT-002"><ENAMEX type="PERSON" id="PER-112233-002">Thomas Jefferson</ENAMEX> has a social security number of <IDEX type="SSN" id="SSN-112233-075">222-22-2222</IDEX>.</S>
</TXT>
</DOC>
</NORMDOC>
"""
tree = ET.parse(xml_doc) # xml_doc is actually a file, but for reproducability it's the above xml
然后我想从那里提取 TXT 中的所有内容作为去除标签的字符串。它必须是后面一些其他进程的字符串。我想看起来像下面的output_txt。
output_txt = "George Washington and Thomas Jefferson were both founding fathers. Thomas Jefferson has a social security number of 222-22-2222."
我想这应该相当简单明了,但我就是想不通。我尝试使用this 解决方案,但我得到了AttributeError: 'ElementTree' object has no attribute 'itertext',它会剥离xml 中的所有标签,而不是仅在<TXT> 和</TXT> 之间。
【问题讨论】:
-
我使用
itertext没有问题,所以最好显示完整的错误消息和给出此错误的代码。您当前的示例没有给出此错误。
标签: python xml elementtree