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

如何为Jupyter Lab中Spacy NER可视化组件displacy添加点击交互功能

实现方案

该方案完全基于Jupyter Lab原生能力和ipywidgets实现,无需启动额外Web服务,可直接在Jupyter Hub环境运行。

依赖安装

先确保安装所需依赖:

pip install spacy beautifulsoup4 ipywidgets
# 若Jupyter Lab未加载ipywidgets扩展,执行以下命令安装后重启Lab即可
jupyter labextension install @jupyter-widgets/jupyterlab-manager

完整可运行代码

import spacy
from spacy import displacy
from bs4 import BeautifulSoup
import ipywidgets as widgets
from IPython.display import display

# 1. 处理文本获取NER结果
nlp = spacy.load("en_core_web_sm")
text = "When Sebastian Thrun started working on self-driving cars at Google in 2007, few people outside of the company took him seriously."
doc = nlp(text)

# 2. 获取displacy生成的原始HTML,注意jupyter参数为布尔值False而非字符串
raw_html = displacy.render(doc, style="ent", jupyter=False)

# 3. 解析HTML给实体标签添加自定义属性和可点击样式
soup = BeautifulSoup(raw_html, "html.parser")
for ent_tag in soup.find_all("mark", class_="entity"):
    ent_text = ent_tag.contents[0].strip()
    ent_label = ent_tag.find("span", class_="label").text.strip()
    # 存储实体信息到自定义属性,方便JS读取
    ent_tag["data-entity-text"] = ent_text
    ent_tag["data-entity-label"] = ent_label
    # 添加鼠标指针样式提示可点击
    ent_tag["style"] = ent_tag.get("style", "") + "cursor: pointer;"
modified_html = str(soup)

# 4. 声明组件和自定义回调函数
html_widget = widgets.HTML(value=modified_html)
output = widgets.Output()

# 自定义点击触发的业务逻辑,可按需修改
def on_entity_click(entity_text, entity_label):
    with output:
        output.clear_output()
        print(f"点击实体内容:{entity_text},实体类型:{entity_label}")
        # 此处可添加你需要的任意交互逻辑,比如查询实体详情、修改标注、联动其他组件等

# 5. 注入JS绑定点击事件,实现前端到Python内核的消息传递
js_code = """
<script>
document.querySelectorAll('.entity').forEach(entEl => {
    entEl.onclick = function() {
        const text = this.dataset.entityText;
        const label = this.dataset.entityLabel;
        // 调用Python侧的回调函数,处理单引号转义避免执行报错
        IPython.notebook.kernel.execute(`on_entity_click('${text.replace(/'/g, "\\'")}', '${label.replace(/'/g, "\\'")}')`);
    }
})
</script>
"""
html_widget.value += js_code

# 渲染可视化组件和输出组件
display(html_widget, output)

注意事项

  • 如果需要更复杂的双向交互,可以改用ipywidgets的jslink关联实体标签属性和自定义widget属性,适配更复杂的联动场景
  • 代码中已默认处理实体内容的单引号转义,避免JS执行异常,若存在其他特殊字符可自行补充转义规则

内容的提问来源于stack exchange,提问作者JFerro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 15:09:02