0

我正在使用 Streamlit 突出显示文本中的不同关键字,因此我将关键字包装在其中, <span style="background-color: #XXXXXX"> keyword </span>但由于某些关键字是短语,因此我最终会在一些文本中添加<span>类似的<span>内容

<span style="background-color:FFFF000"> The quick brown fox <span style..>jumps</span> over the lazy dog </span>

这会导致在此字符串中解析 Markdown 或 HTML 时出错:

我正在考虑定义一个函数来传递字符串并删除内部跨度以防万一

def html_debugger(text):
    magic
    return text

这会返回<span style="background-color:FFFF000"> The quick brown fox jumps over the lazy dog </span> ,但我不确定如何看待这个函数

4

1 回答 1

1

两种做法,

首先使用标准库re,它应该适用于任何类型的标签,不仅是span

import re

html = """<span style="background-color:FFFF000"> The quick brown fox <span style="test">jumps</span> over the lazy dog </span>"""

def html_debugger(text):
    tag_pattern = r'<[^>]*>'
    tags = re.findall(tag_pattern, text)
    inside_text = re.sub(tag_pattern, '', text)
    
    return tags[0] + inside_text + tags[-1]

html_debugger(html)
# '<span style="background-color:FFFF000"> The quick brown fox jumps over the lazy dog </span>'

第二个是BeautifulSoup

from bs4 import BeautifulSoup

html = """<span style="background-color:FFFF000"> The quick brown fox <span style="test">jumps</span> over the lazy dog </span>"""

def html_debugger(text):
    bs_span = BeautifulSoup(text)
    span = s.find_all('span')[0]
    
    span_text = span.text
    span_style = span.attrs['style']
    
    return f'<span style="{span_style}">{span_text}</span>'

html_debugger(html)
# '<span style="background-color:FFFF000"> The quick brown fox jumps over the lazy dog </span>'
于 2020-09-23T22:07:18.727 回答