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)
运行结果: