python - 如何使用自定义标记颜色将每个句子包装在标签中?

标签 python html css web-scraping beautifulsoup

我正在使用漂亮的汤并请求加载网站的 HTML(例如 https://en.wikipedia.org/wiki/Elephant)。我想模仿这个页面,但我想为“p”标签(段落)中的句子着色。

为此,我使用 spacy 将文本分解成句子。我选择一种颜色(感兴趣的人可以选择基于二元深度学习分类器的概率颜色)。

def get_colorized_p(p):
    
    doc = nlp(p.text) # p is the beautiful soup p tag
    string = '<p>'
    for sentence in doc.sents:
        # The prediction value in anything within 0 to 1.
        prediction = classify(sentence.text, model=model, pred_values=True)[1][1].numpy()
        # I am using a custom function to map the prediction to a hex colour.
        color = get_hexcolor(prediction)
        string += f'<mark style="background: {color};">{sentence.text} </mark> '
    string += '</p>'
    return string # I create a new long string with the markup

我在 p 标签内创建了一个带有 HTML 标记的新长字符串。我现在想替换漂亮汤对象中的“旧”元素。 我用一个简单的循环来做到这一点:

for element in tqdm_notebook(soup.findAll()):
    if element.name == 'p':
        if len(element.text.split()) > 2: 
            element = get_colorized_p(element)

这不会给出任何错误,但是当我呈现 HTML 文件时。显示的 HTML 文件没有标记

我正在使用 jupyter 快速显示 HTML 文件:

from IPython.display import display, HTML

display(HTML(html_file))

但是这不起作用。我确实通过 get_colorized_p 验证了返回的字符串。当我在单个 p 元素上使用它并渲染它时,它工作正常。但我想将字符串插入到漂亮的汤对象中。

我希望任何人都可以阐明这个问题。在循环内替换元素会出错。但是,我不知道如何修复它。

以防万一的渲染字符串示例:

<p><mark style="background: #edf8fb;">Elephants are the largest existing land animals.</mark><mark style="background: #f1fafc;">Three living species are currently recognised: the African bush elephant, the African forest elephant, and the Asian elephant.</mark><mark style="background: #f3fafc;">They are an informal grouping within the proboscidean family Elephantidae.</mark><mark style="background: #f3fafc;">Elephantidae is the only surviving family of proboscideans; extinct members include the mastodons.</mark><mark style="background: #eff9fb;">Elephantidae also contains several extinct groups, including the mammoths and straight-tusked elephants.</mark><mark style="background: #68c3a6;">African elephants have larger ears and concave backs, whereas Asian elephants have smaller ears, and convex or level backs.</mark><mark style="background: #56ba91;">The distinctive features of all elephants include a long proboscis called a trunk, tusks, large ear flaps, massive legs, and tough but sensitive skin.</mark><mark style="background: #d4efec;">The trunk is used for breathing, bringing food and water to the mouth, and grasping objects.</mark><mark style="background: #e7f6f9;">Tusks, which are derived from the incisor teeth, serve both as weapons and as tools for moving objects and digging.</mark><mark style="background: #d9f1f0;">The large ear flaps assist in maintaining a constant body temperature as well as in communication.</mark><mark style="background: #e5f5f9;">The pillar-like legs carry their great weight.</mark><mark style="background: #72c7ad;"> </mark></p>

最佳答案

就像那个想法和配色方案 - 我认为主要问题是您尝试用 string 替换 tag,而您应该 replace_with( ) 一个 bs4 对象 来为你的soup 增添新 flavor :

for element in tqdm_notebook(soup.find_all()):
    if element.name == 'p':
        if len(element.text.split()) > 2: 
            element.replace_with(BeautifulSoup(get_colorized_p(element), 'html.parser'))

将您的 soup 转换回字符串并尝试显示它:

display(HTML(str(soup)))

在较新的代码中,避免使用旧语法 findAll(),而是使用 find_all() - 如需更多信息,请花一分钟时间至 check docs

例子
from bs4 import BeautifulSoup
from IPython.display import display, HTML

html = '''
    <p>Elephants are the largest ...</p>
'''
soup = BeautifulSoup(html, 'html.parser')

def get_colorized_p(element):
    ### processing and returning of result str
    return '<p><mark style="background: #edf8fb;">Elephants are the largest existing land animals.</mark><mark style="background: #f1fafc;">Three living species are currently recognised: the African bush elephant, the African forest elephant, and the Asian elephant.</mark><mark style="background: #f3fafc;">They are an informal grouping within the proboscidean family Elephantidae.</mark><mark style="background: #f3fafc;">Elephantidae is the only surviving family of proboscideans; extinct members include the mastodons.</mark><mark style="background: #eff9fb;">Elephantidae also contains several extinct groups, including the mammoths and straight-tusked elephants.</mark><mark style="background: #68c3a6;">African elephants have larger ears and concave backs, whereas Asian elephants have smaller ears, and convex or level backs.</mark><mark style="background: #56ba91;">The distinctive features of all elephants include a long proboscis called a trunk, tusks, large ear flaps, massive legs, and tough but sensitive skin.</mark><mark style="background: #d4efec;">The trunk is used for breathing, bringing food and water to the mouth, and grasping objects.</mark><mark style="background: #e7f6f9;">Tusks, which are derived from the incisor teeth, serve both as weapons and as tools for moving objects and digging.</mark><mark style="background: #d9f1f0;">The large ear flaps assist in maintaining a constant body temperature as well as in communication.</mark><mark style="background: #e5f5f9;">The pillar-like legs carry their great weight.</mark><mark style="background: #72c7ad;"> </mark></p>'

for element in soup.find_all():
    if element.name == 'p':
        if len(element.text.split()) > 2: 
            element.replace_with(BeautifulSoup(get_colorized_p(element), 'html.parser'))

display(HTML(str(soup)))

不完全相同但非常接近您问题中的行为:How to wrap initial of each word in a specific tag with a <b>?

关于python - 如何使用自定义标记颜色将每个句子包装在标签中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72416799/

相关文章:

html - 网页在 Chrome、Firefox、Safari、Not I.E 中显示

css - 字体系列未加载?

python - 通过 python 插入数据时如何处理 google 工作表中的配额超出错误 429?

python - 对前十名结果进行排序

python - 为字典预分配内存?

html - css max-width 不工作,br 在最大宽度之后

Python:根据 DST 获取时间戳的时区

php - 我的 ISSET 后期功能不起作用,无法确定原因

html - 将两个div并排放置后,右边的在最下面

javascript - Canvas:使用drawImage捕获流只捕获流图像的左上角