【问题标题】:Create raw text from XML tags从 XML 标记创建原始文本
【发布时间】: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 中的所有标签,而不是仅在&lt;TXT&gt;&lt;/TXT&gt; 之间。

【问题讨论】:

  • 我使用itertext 没有问题,所以最好显示完整的错误消息和给出此错误的代码。您当前的示例没有给出此错误。

标签: python xml elementtree


【解决方案1】:

通常我会使用纯 XPath 来执行此操作:

normalize-space(//TXT)

但是,ElementTree 中的 XPath 支持是有限的,因此您只能在 lxml 中执行此操作。

要在 ElementTree 中执行此操作,我会执行类似于您在问题中链接到的答案;使用method="text" 将其强制为带有tostring 的纯文本。您还想规范化空白。

示例...

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.fromstring(xml_doc)

txt = tree.find(".//TXT")
raw_text = ET.tostring(txt, encoding='utf8', method='text').decode()
normalized_text = " ".join(raw_text.split())
print(normalized_text)

打印输出...

George Washington and Thomas Jefferson were both founding fathers. Thomas Jefferson has a social security number of 222-22-2222.

【讨论】:

  • 看起来与我正在寻找的完全一样,我认为您无法在 ElementTree 中执行类似于 XPath 的操作。谢谢!
猜你喜欢
  • 2021-07-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-26
  • 1970-01-01
  • 1970-01-01
  • 2021-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多