基于知识树的知识库构建与查询的例子

import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

# 示例对话记录
dialogue = """
客户:你好,我想了解一下产品的保修政策。
坐席:您好!我们的产品保修期为一年,从购买之日起计算。
客户:如果产品在保修期内出现故障,我该怎么办?
坐席:您可以在保修期内将产品送到我们指定的维修点进行免费维修。
客户:维修点在哪里?
坐席:您可以在我们的官方网站上查询最近的维修点地址。
客户:好的,谢谢!
坐席:不客气,祝您生活愉快!
"""

# 解析对话内容并构建知识树
def parse_dialogue(dialogue):
    lines = dialogue.splitlines()
    tree = nx.DiGraph()
    
    # 核心理念(树干)
    root = "产品保修咨询"
    tree.add_node(root)
    
    # 方法论(树枝)和具体案例(树叶)
    questions = {
        "我想了解一下产品的保修政策。": "产品保修期为一年,从购买之日起计算。",
        "如果产品在保修期内出现故障,我该怎么办?": "您可以在保修期内将产品送到我们指定的维修点进行免费维修。",
        "维修点在哪里?": "您可以在我们的官方网站上查询最近的维修点地址。"
    }
    
    for question, answer in questions.items():
        tree.add_node(question)
        tree.add_edge(root, question)
        tree.add_node(answer)
        tree.add_edge(question, answer)
    
    return tree

# 构建知识树
knowledge_tree = parse_dialogue(dialogue)

# 设置字体路径
font_path = "/System/Library/Fonts/STHeiti Light.ttc"  # macOS系统自带的黑体字体路径
font_prop = FontProperties(fname=font_path)

# 可视化知识树
def visualize_tree(tree):
    pos = nx.spring_layout(tree, k=0.5, iterations=20)  # 节点布局
    nx.draw(tree, pos, with_labels=True, node_size=500, node_color="skyblue", font_size=8, font_weight='bold', font_family=font_prop.get_name())
    plt.title("知识树", fontproperties=font_prop)
    plt.axis('off')  # 关闭坐标轴
    plt.show()

# 查询功能
def query_knowledge_tree(tree, question):
    for node in tree.nodes():
        if question in node:
            successors = nx.descendants(tree, node)
            if successors:
                return successors
    return None

# 测试查询功能
question = "如果产品在保修期内出现故障,我该怎么办?"
result = query_knowledge_tree(knowledge_tree, question)
print(question)
if result:
    print(f"树查询结果:")
    for node in result:
        print(node)
else:
    print("未找到相关问题的答案。")

# 可视化知识树
visualize_tree(knowledge_tree)

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jacky_wxl(微信同号)

喜欢作者

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值