【问题标题】:Removing text from multiple <p> tags from each <article> in xml从xml中每个<article>的多个<p>标签中删除文本
【发布时间】:2022-02-09 20:26:54
【问题描述】:

我正在努力解决这个问题,该文件的根为“articles”,并且在标签“article>”下包含许多单独的文章。我希望做的是为“文章”中的每个“文章”收集“p”标签中的所有文本。一个“文章”可以有多个“p”标签,如下所示:

<articles>
    <article title="Blah" published-at="2018-01-01" id="00000">
      <p>Here is some text.</p>
      <p>Another line of text.</p>
      <a type="external" href="https://www.website.com/">Image</a>
      <p>Final line of text.</p>
    </article>
    <article title="Second blah" published-at="2018-01-02" id="00001">
      <p>Here is some new text.</p>
      <p>Final line of new text.</p>
    </article>
</articles>

所以我想做的是遍历每篇文章并生成包含“p”标签中所有文本的单行,而不关心我是否在“a”标签中拾取链接和相关文本。

我希望这样的事情能奏效,但它生成的文本文件没有被每个“文章”分隔

text = []

for p in root.iter('p'):
  text.append(p.text)
  with open("text.txt", "w", encoding = 'utf-8') as output:
    output.write(str(text))

任何帮助将不胜感激,因为这对我来说是一个很难在搜索中表达的问题。

【问题讨论】:

    标签: xml python-3.x


    【解决方案1】:

    Python 有 xml.etree.ElementTree 库(以及其他)用于处理 XML,您可以使用它:

    import xml.etree.ElementTree as ET
    tree = ET.parse('test.xml')
    root = tree.getroot()
    
    text = []
    for article in root.findall('article'):
        for paragraph in article.findall('p'):
            text.append(paragraph.text)
            paragraph.text = ''
    
    tree.write('output.xml')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多