从XML标记创建原始文本

2024-06-02 15:04:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些通过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>之间。你知道吗


Tags: 字符串txtid内容doctypethomasxml
1条回答
网友
1楼 · 发布于 2024-06-02 15:04:20

通常我会使用纯XPath来实现:

normalize-space(//TXT)

但是,ElementTree中的XPath支持是有限的,因此只能在lxml中实现。你知道吗

要在ElementTree中实现它,我会像你在问题中链接到的答案一样;使用method="text"强制它为纯文本。您还需要规范化空白。你知道吗

示例。。。你知道吗

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.

相关问题 更多 >