从自由流动的文本中删除html标记以形成单独的句子

2024-05-13 20:27:24 发布

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

我想从一大块课文中摘录句子。我的短信大概是

<ul><li>Registered Nurse in <font>Missouri</font>, License number <font>xxxxxxxx</font>, <font>2017</font></li><li>AHA Advanced Cardiac Life Support (ACLS) Certification <font>2016-2018</font></li><li>AHA PALS - Pediatric Advanced Life Support 2017-2019</li><li>AHA Basic Life Support 2016-2018</li></ul>

我想从上面的课文中摘录适当的句子。因此,预期产出将是一个列表

^{pr2}$

我使用python内置的HTMLParser模块从上面的文本中剥离htmls。这是我的密码。在

class HTMLStripper(HTMLParser):

    def __init__(self):
        super().__init__()
        self.reset()
        self.strict = False
        self.convert_charrefs= True
        self.fed = []

    def handle_data(self, chunk):
        #import pdb; pdb.set_trace()
        self.fed.append(chunk.strip())

    def get_data(self):
        return [x for x in self.fed if x]


def strip_html_tags(html):
    try:
        s = HTMLStripper()
        s.feed(html)
        return s.get_data()
    except Exception as e:
        # Remove html strings from the given string
        p = re.compile(r'<.*?>')
        return p.sub('', html)

它给出了对上面的文本调用strip_html_tags函数的以下结果(这实际上是当前实现应该产生的输出)

['Registered Nurse in', 'Missouri', ', License number', 'xxxxxxx', ',', '2017', 'AHA Advanced Cardiac Life Support (ACLS) Certification', '2016-2018', 'AHA PALS - Pediatric Advanced Life Support 2017-2019', 'AHA Basic Life Support 2016-2018']

我不能严格检查<ul> or <li> tags,因为不同的文本可能有不同的html标记。我有一种方法可以像上面那样在外部html-tags上拆分文本,而不是在遇到的每个html-tag上进行拆分

提前谢谢。在


Tags: in文本selfsupportdatadefhtmltags
2条回答

经过深思熟虑,我把我的解决方案张贴在这里。对于我所举的各种例子来说,它的效果非常好。如果我事先知道必须从中提取文本的标记,那么使用BeautifulSoup的方法就可以工作了(这样我就可以应用soup.findAll(specific_tag)),但我的情况并非如此。他们也可以是多个标签,我必须从那里提取文本。例如-

<p>Science</p><div> Biology </div><div>Generation of mature T cells from human hematopoietic stem and progenitor cells in artificial thymic organoids. <span style=\"text-decoration: underline;\">Nature Methods</span> 2017,</div>

在上面的例子中,我想从<p>标记和<div>标记中提取文本。在

我修改了上面的代码来处理这种情况-

^{pr2}$

在上面的例子中运行代码

parser = HTMLStripper()
parser.feed(mystr)
l1 = parser.get_tree()
feed = parser.get_data()
print(l1)
print("\n", mystr)
print("\n", feed)
print("\n\n")

而输出-

[['ul'], ['li', 'li'], ['li', 'li'], ['li', 'li'], ['li', 'li'], ['ul']]

<ul><li>Registered Nurse in <font>Missouri</font>, License number <font>xxxxxxxx</font>, <font>2017</font></li><li>AHA Advanced Cardiac Life Support (ACLS) Certification <font>2016-2018</font></li><li>AHA PALS - Pediatric Advanced Life Support 2017-2019</li><li>AHA Basic Life Support 2016-2018</li></ul>

['Registered Nurse in Missouri , License number xxxxxxxx , 2017', 'AHA Advanced Cardiac Life Support (ACLS) Certification 2016-2018', 'AHA PALS - Pediatric Advanced Life Support 2017-2019', 'AHA Basic Life Support 2016-2018']

也适用于混合标记html字符串-

[['p', 'p'], ['div', 'div'], ['div', 'span', 'span', 'div']]

<p>Science</p><div> Biology </div><div>Generation of mature T cells from human hematopoietic stem and progenitor cells in artificial thymic organoids. <span style="text-decoration: underline;">Nature Methods</span> 2017,</div>

['Science', 'Biology', 'Generation of mature T cells from human hematopoietic stem and progenitor cells in artificial thymic organoids. Nature Methods 2017,']

很想看到一个角落的情况,这样我可以改进文字提取逻辑。在

为什么不使用已经可以有效解析html的工具呢?比如BeautifulSoup

from bs4 import BeautifulSoup

demo = '<ul><li>Registered Nurse in <font>Missouri</font>, License number <font>xxxxxxxx</font>, <font>2017</font></li><li>AHA Advanced Cardiac Life Support (ACLS) Certification <font>2016-2018</font></li><li>AHA PALS - Pediatric Advanced Life Support 2017-2019</li><li>AHA Basic Life Support 2016-2018</li></ul>'
soup = BeautifulSoup(demo, 'lxml')
sentences = [item.text for item in soup.findAll('li')]

变量sentences现在正好可以容纳您想要的,请您自己测试

根据您的评论,我将使用以下代码:

^{pr2}$

所以现在您不再需要担心标记了,只需要一个简单的字符串,然后您可以将其转换为一个以split(',')作为逗号的列表(但是如果文本不总是带有逗号或点,我就不麻烦了,只需使用字符串本身)

注意:如果没有文本的某些已知结构,就不可能总是以相同的方式解析它并获得已知的结果。这个已知的结构可以是某些html标记,也可以是您事先知道的某些文本特性

相关问题 更多 >