交互式知识图谱

写于

用pyvis生成交互式知识图谱

可以生成可拖拽、可点击展开的网页版图谱,适合分享给学生,核心逻辑和networkx类似,只是可视化输出为 HTML 文件

import networkx as nx
from pyvis.network import Network
import re

def parse_contents_to_graph(file_path):
    """解析contents2.md文件并构建知识图谱"""
    G = nx.Graph()

    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()

    # 按章节分割内容
    chapters = re.split(r'\n\d+\.\s', content)[1:]  # 跳过第一个空元素

    # 添加节点和边
    for i, chapter in enumerate(chapters):
        lines = chapter.strip().split('\n')
        chapter_title = lines[0].strip()

        # 添加章节节点
        G.add_node(chapter_title, group="chapter", size=30, color="#FF6B6B")

        # 添加节节点和边
        for line in lines[1:]:
            if line.strip().startswith('- '):
                section = line.strip()[2:]  # 去掉 "- " 前缀
                G.add_node(section, group="section", size=20, color="#4ECDC4")
                G.add_edge(chapter_title, section)

    return G

def create_interactive_network(G, output_file="内科护理学知识网络_pyvis.html"):
    """使用pyvis创建交互式网络图"""
    # 创建pyvis网络对象
    net = Network(
        height="800px", 
        width="100%", 
        bgcolor="#ffffff", 
        font_color="#000000",
        directed=False
    )

    # 从networkx图转换
    net.from_nx(G)

    # 自定义节点样式
    for node in net.nodes:
        if node['group'] == 'chapter':
            node['color'] = '#FF6B6B'  # 章节节点红色
            node['size'] = 30
        elif node['group'] == 'section':
            node['color'] = '#4ECDC4'  # 节节点青色
            node['size'] = 20

    # 设置物理参数以获得更好的布局
    net.set_options("""
    {
      "physics": {
        "enabled": true,
        "stabilization": {
          "iterations": 100
        }
      },
      "interaction": {
        "dragNodes": true,
        "dragView": true,
        "zoomView": true,
        "selectConnectedEdges": true
      }
    }
    """)

    # 保存为HTML文件
    net.save_graph(output_file)
    print(f"交互式知识图谱已保存至: {output_file}")
    return output_file

def main():
    # 解析内容文件并构建图
    G = parse_contents_to_graph("contents2.md")

    # 创建交互式网络图
    output_file = create_interactive_network(G)

    print("✅ 知识网络已成功导出:")
    print(f"  - 交互式HTML:{output_file}")
    print("\n功能说明:")
    print("  - 拖拽节点:可以拖动节点到任意位置")
    print("  - 缩放视图:使用鼠标滚轮缩放")
    print("  - 拖拽画布:按住空白处拖拽整个画布")
    print("  - 节点选择:点击节点查看连接关系")
    print("  - 物理模拟:节点会自动调整到合适位置")

if __name__ == "__main__":
    main()