使用Beautifulsoup处理后,段落合并

时间:2019-05-23 10:27:39

标签: python beautifulsoup

我的任务是突出显示html文件中的某些单词。这可以很好地工作,但是不幸的是,结果文件中的段落从某个角度开始合并在一起(因此,我得到了没有空白行的纯文本),这看起来很难看。我真的不明白其原因,尤其是因为这种现象不是在文件的开头出现,而是从中间的某个点开始出现(因此文件的第一部分很好,第二部分很丑)。代码如下:

with open(file_in, 'r', encoding='utf8') as f:
   source = f.read()
soup = BeautifulSoup(source, 'html.parser')
for tag in soup:
    if type(tag) is not bs4.element.Tag:
        continue
    if ll[1]<90:
        new_soup = BeautifulSoup(str(tag).replace(ll[0], '<span    style="background-color:yellow">'+ll[0]+'</span>'))
    else:
        new_soup = BeautifulSoup(str(tag).replace(ll[0], '<span style="background-color:red">'+ll[0]+'</span>'))
    tag.replace_with(new_soup)
with open(file_out, 'w', encoding='utf8') as f:
    f.write(str(soup))

因此,file_in完全不错,但从中间的某个点看,file_out却很丑陋,因为整个文本被合并为一个整体。 有人知道我该如何预防? 预先感谢。

0 个答案:

没有答案