You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python前端库实现文本高亮标注命名组件?

用Streamlit实现带命名高亮文本块的组件

核心实现思路

借助Streamlit支持嵌入HTML和CSS的特性,通过自定义样式实现高亮文本块及顶部命名标签的效果,无需额外第三方组件。

具体实现代码与步骤

  • 定义自定义CSS样式,分别控制高亮块的背景样式和名称标签的定位、外观
  • 封装复用函数,接收完整文本、高亮区间(含起始/结束索引、名称)参数
  • 在Streamlit应用中调用函数,传入目标文本和高亮配置
import streamlit as st

def render_highlighted_text(full_text, highlight_configs):
    # 注入自定义CSS样式
    custom_style = """
    <style>
        .highlighted-section {
            position: relative;
            background: #e8f4fd;
            padding: 3px 5px;
            border-radius: 4px;
        }
        .section-label {
            position: absolute;
            top: -18px;
            left: 5px;
            font-size: 12px;
            background: #339af0;
            color: white;
            padding: 2px 7px;
            border-radius: 3px;
            font-weight: 600;
        }
    </style>
    """
    st.markdown(custom_style, unsafe_allow_html=True)
    
    # 从后往前处理高亮块,避免索引偏移
    processed_content = full_text
    for config in reversed(highlight_configs):
        start, end, label = config
        highlighted_segment = f'<span class="highlighted-section"><span class="section-label">{label}</span>{full_text[start:end]}</span>'
        processed_content = processed_content[:start] + highlighted_segment + processed_content[end:]
    
    st.markdown(processed_content, unsafe_allow_html=True)

# 示例使用
if __name__ == "__main__":
    st.header("带命名高亮的文本展示组件")
    demo_text = "Python是一种高级编程语言,以简洁易读的语法著称,广泛应用于数据科学、Web开发、人工智能等多个领域。"
    # 高亮配置:(起始索引, 结束索引, 标签名称)
    highlight_settings = [
        (0, 6, "编程语言"),
        (16, 26, "核心特性"),
        (36, 66, "应用领域")
    ]
    render_highlighted_text(demo_text, highlight_settings)

扩展说明

  • 若需要区分不同类型的高亮块,可在函数中添加颜色参数,动态生成对应CSS类
  • 索引可通过字符串查找函数(如str.find())自动获取,无需手动计算
  • 若要支持交互(如点击标签显示更多信息),可结合Streamlit的回调函数实现

内容的提问来源于stack exchange,提问作者Vivek V Krishnan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 02:20:25