python - beautifulsoup findall

标签 python xml beautifulsoup

我有一些 xml:

<article>
<uselesstag></uslesstag>
<topic>oil, gas</topic>
<body>body text</body>
</article>

<article>
<uselesstag></uslesstag>
<topic>food</topic>
<body>body text</body>
</article>

<article>
<uselesstag></uslesstag>
<topic>cars</topic>
<body>body text</body>
</article>

有很多很多无用的标签。 我想使用 beautifulsoup 收集正文标签中的所有文本及其关联的主题文本,以创建一些新的 xml。

我是 python 的新手,但我怀疑某种形式的

import arff
from xml.etree import ElementTree
import re
from StringIO import StringIO

import BeautifulSoup
from BeautifulSoup import BeautifulSoup

totstring=""

with open('reut2-000.sgm', 'r') as inF:
    for line in inF:
        string=re.sub("[^0-9a-zA-Z<>/\s=!-\"\"]+","", line)
    totstring+=string


soup = BeautifulSoup(totstring)

body = soup.find("body")



for anchor in soup.findAll('body'):
    #Stick body and its topics in an associated array?




file.close

会起作用。

1) 我该怎么做? 2) 我应该向 XML 添加根节点吗?否则它不是正确的 XML 是吗?

非常感谢

编辑:

我想要结束的是:

<article>
<topic>oil, gas</topic>
<body>body text</body>
</article>

<article>
<topic>food</topic>
<body>body text</body>
</article>

<article>
<topic>cars</topic>
<body>body text</body>
</article>

有很多很多无用的标签。

最佳答案

好的。这是解决方案,

首先,确保你安装了“beautifulsoup4”:http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-beautiful-soup

这是我获取所有正文和主题标签的代码:

from bs4 import BeautifulSoup
html_doc= """
<article>
<topic>oil, gas</topic>
<body>body text</body>
</article>

<article>
<topic>food</topic>
<body>body text</body>
</article>

<article>
<topic>cars</topic>
<body>body text</body>
</article>
"""
soup = BeautifulSoup(html_doc)

bodies = [a.get_text() for a in soup.find_all('body')]
topics = [a.get_text() for a in soup.find_all('topic')]

关于python - beautifulsoup findall,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10519025/

相关文章:

python - 两个正数相乘在 Python 3 中给出负输出

python - 是否有 Pythonic 泛型 "null dependency"?

ruby-on-rails - 如何从少数 XML 节点中删除命名空间

java - JDOM 将内容写入现有文件而不删除

python - 使用 Python、Selenium、Beautiful Soup 扩展 DOM 列表以提取附加内容

Python/BeautifulSoup 中的多线程抓取根本没有加速

python - BeautifulSoup:在 html 中查找特定 URL 并打印

python - Python 中的 __del__() 方法有什么用?

python - 使用 SQLObject ORM 筛选 "value in list"

c++ - 如何使用 libcurl C++ 从 url 保存 XML 文件