当前位置:   article > 正文

Python 医学知识图谱问答系统(一),建立医学知识图谱,基于neo4j知识图谱的医学问答体系_基于noej4医药知识图谱

基于noej4医药知识图谱

医学知识问答,知识图谱建设部分,建设过程如下:

一.首先,准备数据,主要为结构化的医学数据,包含实体和关系

原始数据样式(来源于刘焕勇老师整理的医学数据):

 二.在neo4j数据库中建立空数据库,并且启用数据库,我这里用的是桌面版的neo4j,效果如下:

用户名:neo4j,密码:123456,大家根据自己需求设定,启用数据库:

 三.开始写Python将数据导入数据库

  1. import os
  2. import json
  3. from py2neo import Graph,Node

1.设置文件读取路径:

  1. cur_dir = '/'.join(os.path.abspath(__file__).split('/')[:-1])
  2. data_path = os.path.join(cur_dir, 'data/medical.json')

2.连接数据库设置:

  1. g = Graph(
  2. host="127.0.0.1", # neo4j 搭载服务器的ip地址,ifconfig可获取到
  3. http_port=7474, # neo4j 服务器监听的端口号
  4. user="neo4j", # 数据库user name,如果没有更改过,应该是neo4j
  5. password="123456")

3.读取文件函数,根据实体类型(药品、食物、检查、科室、药品大类、疾病、症状)和关系类型(科室和科室关系、疾病和食物禁忌关系、疾病和宜吃食物关系、疾病和建议食物关系、疾病和通用药品关系、疾病和建议药品关系、疾病和检查的关系、药品和生产厂家的关系、疾病和症状的关系、疾病和并发症的关系、疾病和科室的关系)建立相应的空列表,把他们装起来:

  1. '''读取文件'''
  2. def read_nodes(self):
  3. # 共7类节点
  4. drugs = [] # 药品
  5. foods = [] # 食物
  6. checks = [] # 检查
  7. departments = [] #科室
  8. producers = [] #药品大类
  9. diseases = [] #疾病
  10. symptoms = []#症状
  11. disease_infos = []#疾病信息
  12. # 构建节点实体关系
  13. rels_department = [] # 科室-科室关系
  14. rels_noteat = [] # 疾病-忌吃食物关系
  15. rels_doeat = [] # 疾病-宜吃食物关系
  16. rels_recommandeat = [] # 疾病-推荐吃食物关系
  17. rels_commonddrug = [] # 疾病-通用药品关系
  18. rels_recommanddrug = [] # 疾病-热门药品关系
  19. rels_check = [] # 疾病-检查关系
  20. rels_drug_producer = [] # 厂商-药物关系
  21. rels_symptom = [] #疾病症状关系
  22. rels_acompany = [] # 疾病并发关系
  23. rels_category = [] # 疾病与科室之间的关系
  24. count = 0
  25. for data in open(self.data_path):
  26. disease_dict = {}
  27. count += 1
  28. print(count)
  29. data_json = json.loads(data)
  30. disease = data_json['name']
  31. disease_dict['name'] = disease
  32. diseases.append(disease)
  33. disease_dict['desc'] = ''
  34. disease_dict['prevent'] = ''
  35. disease_dict['cause'] = ''
  36. disease_dict['easy_get'] = ''
  37. disease_dict['cure_department'] = ''
  38. disease_dict['cure_way'] = ''
  39. disease_dict['cure_lasttime'] = ''
  40. disease_dict['symptom'] = ''
  41. disease_dict['cured_prob'] = ''
  42. if 'symptom' in data_json:
  43. symptoms += data_json['symptom']
  44. for symptom in data_json['symptom']:
  45. rels_symptom.append([disease, symptom])
  46. if 'acompany' in data_json:
  47. for acompany in data_json['acompany']:
  48. rels_acompany.append([disease, acompany])
  49. if 'desc' in data_json:
  50. disease_dict['desc'] = data_json['desc']
  51. if 'prevent' in data_json:
  52. disease_dict['prevent'] = data_json['prevent']
  53. if 'cause' in data_json:
  54. disease_dict['cause'] = data_json['cause']
  55. if 'get_prob' in data_json:
  56. disease_dict['get_prob'] = data_json['get_prob']
  57. if 'easy_get' in data_json:
  58. disease_dict['easy_get'] = data_json['easy_get']
  59. if 'cure_department' in data_json:
  60. cure_department = data_json['cure_department']
  61. if len(cure_department) == 1:
  62. rels_category.append([disease, cure_department[0]])
  63. if len(cure_department) == 2:
  64. big = cure_department[0]
  65. small = cure_department[1]
  66. rels_department.append([small, big])
  67. rels_category.append([disease, small])
  68. disease_dict['cure_department'] = cure_department
  69. departments += cure_department
  70. if 'cure_way' in data_json:
  71. disease_dict['cure_way'] = data_json['cure_way']
  72. if 'cure_lasttime' in data_json:
  73. disease_dict['cure_lasttime'] = data_json['cure_lasttime']
  74. if 'cured_prob' in data_json:
  75. disease_dict['cured_prob'] = data_json['cured_prob']
  76. if 'common_drug' in data_json:
  77. common_drug = data_json['common_drug']
  78. for drug in common_drug:
  79. rels_commonddrug.append([disease, drug])
  80. drugs += common_drug
  81. if 'recommand_drug' in data_json:
  82. recommand_drug = data_json['recommand_drug']
  83. drugs += recommand_drug
  84. for drug in recommand_drug:
  85. rels_recommanddrug.append([disease, drug])
  86. if 'not_eat' in data_json:
  87. not_eat = data_json['not_eat']
  88. for _not in not_eat:
  89. rels_noteat.append([disease, _not])
  90. foods += not_eat
  91. do_eat = data_json['do_eat']
  92. for _do in do_eat:
  93. rels_doeat.append([disease, _do])
  94. foods += do_eat
  95. recommand_eat = data_json['recommand_eat']
  96. for _recommand in recommand_eat:
  97. rels_recommandeat.append([disease, _recommand])
  98. foods += recommand_eat
  99. if 'check' in data_json:
  100. check = data_json['check']
  101. for _check in check:
  102. rels_check.append([disease, _check])
  103. checks += check
  104. if 'drug_detail' in data_json:
  105. drug_detail = data_json['drug_detail']
  106. producer = [i.split('(')[0] for i in drug_detail]
  107. rels_drug_producer += [[i.split('(')[0], i.split('(')[-1].replace(')', '')] for i in drug_detail]
  108. producers += producer
  109. disease_infos.append(disease_dict)
  110. return set(drugs), set(foods), set(checks), set(departments), set(producers), set(symptoms), set(diseases), disease_infos,\
  111. rels_check, rels_recommandeat, rels_noteat, rels_doeat, rels_department, rels_commonddrug, rels_drug_producer, rels_recommanddrug,\
  112. rels_symptom, rels_acompany, rels_category

4.建立节点函数:

  1. '''建立节点'''
  2. def create_node(self, label, nodes):
  3. count = 0
  4. for node_name in nodes:
  5. node = Node(label, name=node_name)
  6. self.g.create(node)
  7. count += 1
  8. print(count, len(nodes))
  9. return

5.创建知识图谱中心疾病的节点:

  1. '''创建知识图谱中心疾病的节点'''
  2. def create_diseases_nodes(self, disease_infos):
  3. count = 0
  4. for disease_dict in disease_infos:
  5. node = Node("Disease", name=disease_dict['name'], desc=disease_dict['desc'],
  6. prevent=disease_dict['prevent'] ,cause=disease_dict['cause'],
  7. easy_get=disease_dict['easy_get'],cure_lasttime=disease_dict['cure_lasttime'],
  8. cure_department=disease_dict['cure_department']
  9. ,cure_way=disease_dict['cure_way'] ,
  10. cured_prob=disease_dict['cured_prob'])
  11. self.g.create(node)
  12. count += 1
  13. print(count)
  14. return

6.创建知识图谱实体节点类型schema:

  1. '''创建知识图谱实体节点类型schema'''
  2. def create_graphnodes(self):
  3. Drugs, Foods, Checks, Departments, Producers, Symptoms, Diseases,
  4. disease_infos,rels_check, rels_recommandeat, rels_noteat, rels_doeat, rels_department,
  5. rels_commonddrug, rels_drug_producer, rels_recommanddrug,rels_symptom, rels_acompany,
  6. rels_category = self.read_nodes()
  7. self.create_diseases_nodes(disease_infos)
  8. self.create_node('Drug', Drugs)
  9. print(len(Drugs))
  10. self.create_node('Food', Foods)
  11. print(len(Foods))
  12. self.create_node('Check', Checks)
  13. print(len(Checks))
  14. self.create_node('Department', Departments)
  15. print(len(Departments))
  16. self.create_node('Producer', Producers)
  17. print(len(Producers))
  18. self.create_node('Symptom', Symptoms)
  19. return

7.创建实体关系边:

  1. '''创建实体关系边'''
  2. def create_graphrels(self):
  3. Drugs, Foods, Checks, Departments, Producers, Symptoms, Diseases, disease_infos, rels_check, rels_recommandeat, rels_noteat, rels_doeat, rels_department, rels_commonddrug, rels_drug_producer, rels_recommanddrug,rels_symptom, rels_acompany, rels_category = self.read_nodes()
  4. self.create_relationship('Disease', 'Food', rels_recommandeat, 'recommand_eat', '推荐食谱')
  5. self.create_relationship('Disease', 'Food', rels_noteat, 'no_eat', '忌吃')
  6. self.create_relationship('Disease', 'Food', rels_doeat, 'do_eat', '宜吃')
  7. self.create_relationship('Department', 'Department', rels_department, 'belongs_to', '属于')
  8. self.create_relationship('Disease', 'Drug', rels_commonddrug, 'common_drug', '常用药品')
  9. self.create_relationship('Producer', 'Drug', rels_drug_producer, 'drugs_of', '生产药品')
  10. self.create_relationship('Disease', 'Drug', rels_recommanddrug, 'recommand_drug', '好评药品')
  11. self.create_relationship('Disease', 'Check', rels_check, 'need_check', '诊断检查')
  12. self.create_relationship('Disease', 'Symptom', rels_symptom, 'has_symptom', '症状')
  13. self.create_relationship('Disease', 'Disease', rels_acompany, 'acompany_with', '并发症')
  14. self.create_relationship('Disease', 'Department', rels_category, 'belongs_to', '所属科室')

8.创建实体关联边

  1. '''创建实体关联边'''
  2. def create_relationship(self, start_node, end_node, edges, rel_type, rel_name):
  3. count = 0
  4. # 去重处理
  5. set_edges = []
  6. for edge in edges:
  7. set_edges.append('###'.join(edge))
  8. all = len(set(set_edges))
  9. for edge in set(set_edges):
  10. edge = edge.split('###')
  11. p = edge[0]
  12. q = edge[1]
  13. query = "match(p:%s),(q:%s) where p.name='%s'and q.name='%s' create (p)-[rel:%s{name:'%s'}]->(q)" % (
  14. start_node, end_node, p, q, rel_type, rel_name)
  15. try:
  16. self.g.run(query)
  17. count += 1
  18. print(rel_type, count, all)
  19. except Exception as e:
  20. print(e)
  21. return

9.导出实体文件,应用于问答系统的建设:

  1. '''导出数据'''
  2. def export_data(self):
  3. Drugs, Foods, Checks, Departments, Producers, Symptoms, Diseases, disease_infos,
  4. rels_check, rels_recommandeat, rels_noteat, rels_doeat, rels_department,
  5. rels_commonddrug, rels_drug_producer, rels_recommanddrug, rels_symptom,
  6. rels_acompany, rels_category = self.read_nodes()
  7. f_drug = open('drug.txt', 'w+')
  8. f_food = open('food.txt', 'w+')
  9. f_check = open('check.txt', 'w+')
  10. f_department = open('department.txt', 'w+')
  11. f_producer = open('producer.txt', 'w+')
  12. f_symptom = open('symptoms.txt', 'w+')
  13. f_disease = open('disease.txt', 'w+')
  14. f_drug.write('\n'.join(list(Drugs)))
  15. f_food.write('\n'.join(list(Foods)))
  16. f_check.write('\n'.join(list(Checks)))
  17. f_department.write('\n'.join(list(Departments)))
  18. f_producer.write('\n'.join(list(Producers)))
  19. f_symptom.write('\n'.join(list(Symptoms)))
  20. f_disease.write('\n'.join(list(Diseases)))
  21. f_drug.close()
  22. f_food.close()
  23. f_check.close()
  24. f_department.close()
  25. f_producer.close()
  26. f_symptom.close()
  27. f_disease.close()
  28. return

全部代码:

  1. import os
  2. import json
  3. from py2neo import Graph,Node
  4. class MedicalGraph:
  5. def __init__(self):
  6. cur_dir = '/'.join(os.path.abspath(__file__).split('/')[:-1])
  7. self.data_path = os.path.join(cur_dir, 'data/medical.json')
  8. self.g = Graph(
  9. host="127.0.0.1", # neo4j 搭载服务器的ip地址,ifconfig可获取到
  10. http_port=7474, # neo4j 服务器监听的端口号
  11. user="neo4j", # 数据库user name,如果没有更改过,应该是neo4j
  12. password="123456")
  13. '''读取文件'''
  14. def read_nodes(self):
  15. # 共7类节点
  16. drugs = [] # 药品
  17. foods = [] # 食物
  18. checks = [] # 检查
  19. departments = [] #科室
  20. producers = [] #药品大类
  21. diseases = [] #疾病
  22. symptoms = []#症状
  23. disease_infos = []#疾病信息
  24. # 构建节点实体关系
  25. rels_department = [] # 科室-科室关系
  26. rels_noteat = [] # 疾病-忌吃食物关系
  27. rels_doeat = [] # 疾病-宜吃食物关系
  28. rels_recommandeat = [] # 疾病-推荐吃食物关系
  29. rels_commonddrug = [] # 疾病-通用药品关系
  30. rels_recommanddrug = [] # 疾病-热门药品关系
  31. rels_check = [] # 疾病-检查关系
  32. rels_drug_producer = [] # 厂商-药物关系
  33. rels_symptom = [] #疾病症状关系
  34. rels_acompany = [] # 疾病并发关系
  35. rels_category = [] # 疾病与科室之间的关系
  36. count = 0
  37. for data in open(self.data_path):
  38. disease_dict = {}
  39. count += 1
  40. print(count)
  41. data_json = json.loads(data)
  42. disease = data_json['name']
  43. disease_dict['name'] = disease
  44. diseases.append(disease)
  45. disease_dict['desc'] = ''
  46. disease_dict['prevent'] = ''
  47. disease_dict['cause'] = ''
  48. disease_dict['easy_get'] = ''
  49. disease_dict['cure_department'] = ''
  50. disease_dict['cure_way'] = ''
  51. disease_dict['cure_lasttime'] = ''
  52. disease_dict['symptom'] = ''
  53. disease_dict['cured_prob'] = ''
  54. if 'symptom' in data_json:
  55. symptoms += data_json['symptom']
  56. for symptom in data_json['symptom']:
  57. rels_symptom.append([disease, symptom])
  58. if 'acompany' in data_json:
  59. for acompany in data_json['acompany']:
  60. rels_acompany.append([disease, acompany])
  61. if 'desc' in data_json:
  62. disease_dict['desc'] = data_json['desc']
  63. if 'prevent' in data_json:
  64. disease_dict['prevent'] = data_json['prevent']
  65. if 'cause' in data_json:
  66. disease_dict['cause'] = data_json['cause']
  67. if 'get_prob' in data_json:
  68. disease_dict['get_prob'] = data_json['get_prob']
  69. if 'easy_get' in data_json:
  70. disease_dict['easy_get'] = data_json['easy_get']
  71. if 'cure_department' in data_json:
  72. cure_department = data_json['cure_department']
  73. if len(cure_department) == 1:
  74. rels_category.append([disease, cure_department[0]])
  75. if len(cure_department) == 2:
  76. big = cure_department[0]
  77. small = cure_department[1]
  78. rels_department.append([small, big])
  79. rels_category.append([disease, small])
  80. disease_dict['cure_department'] = cure_department
  81. departments += cure_department
  82. if 'cure_way' in data_json:
  83. disease_dict['cure_way'] = data_json['cure_way']
  84. if 'cure_lasttime' in data_json:
  85. disease_dict['cure_lasttime'] = data_json['cure_lasttime']
  86. if 'cured_prob' in data_json:
  87. disease_dict['cured_prob'] = data_json['cured_prob']
  88. if 'common_drug' in data_json:
  89. common_drug = data_json['common_drug']
  90. for drug in common_drug:
  91. rels_commonddrug.append([disease, drug])
  92. drugs += common_drug
  93. if 'recommand_drug' in data_json:
  94. recommand_drug = data_json['recommand_drug']
  95. drugs += recommand_drug
  96. for drug in recommand_drug:
  97. rels_recommanddrug.append([disease, drug])
  98. if 'not_eat' in data_json:
  99. not_eat = data_json['not_eat']
  100. for _not in not_eat:
  101. rels_noteat.append([disease, _not])
  102. foods += not_eat
  103. do_eat = data_json['do_eat']
  104. for _do in do_eat:
  105. rels_doeat.append([disease, _do])
  106. foods += do_eat
  107. recommand_eat = data_json['recommand_eat']
  108. for _recommand in recommand_eat:
  109. rels_recommandeat.append([disease, _recommand])
  110. foods += recommand_eat
  111. if 'check' in data_json:
  112. check = data_json['check']
  113. for _check in check:
  114. rels_check.append([disease, _check])
  115. checks += check
  116. if 'drug_detail' in data_json:
  117. drug_detail = data_json['drug_detail']
  118. producer = [i.split('(')[0] for i in drug_detail]
  119. rels_drug_producer += [[i.split('(')[0], i.split('(')[-1].replace(')', '')] for i in drug_detail]
  120. producers += producer
  121. disease_infos.append(disease_dict)
  122. return set(drugs), set(foods), set(checks), set(departments), set(producers), set(symptoms), set(diseases), disease_infos,\
  123. rels_check, rels_recommandeat, rels_noteat, rels_doeat, rels_department, rels_commonddrug, rels_drug_producer, rels_recommanddrug,\
  124. rels_symptom, rels_acompany, rels_category
  125. '''建立节点'''
  126. def create_node(self, label, nodes):
  127. count = 0
  128. for node_name in nodes:
  129. node = Node(label, name=node_name)
  130. self.g.create(node)
  131. count += 1
  132. print(count, len(nodes))
  133. return
  134. '''创建知识图谱中心疾病的节点'''
  135. def create_diseases_nodes(self, disease_infos):
  136. count = 0
  137. for disease_dict in disease_infos:
  138. node = Node("Disease", name=disease_dict['name'], desc=disease_dict['desc'],
  139. prevent=disease_dict['prevent'] ,cause=disease_dict['cause'],
  140. easy_get=disease_dict['easy_get'],cure_lasttime=disease_dict['cure_lasttime'],
  141. cure_department=disease_dict['cure_department']
  142. ,cure_way=disease_dict['cure_way'] , cured_prob=disease_dict['cured_prob'])
  143. self.g.create(node)
  144. count += 1
  145. print(count)
  146. return
  147. '''创建知识图谱实体节点类型schema'''
  148. def create_graphnodes(self):
  149. Drugs, Foods, Checks, Departments, Producers, Symptoms, Diseases, disease_infos,rels_check, rels_recommandeat, rels_noteat, rels_doeat, rels_department, rels_commonddrug, rels_drug_producer, rels_recommanddrug,rels_symptom, rels_acompany, rels_category = self.read_nodes()
  150. self.create_diseases_nodes(disease_infos)
  151. self.create_node('Drug', Drugs)
  152. print(len(Drugs))
  153. self.create_node('Food', Foods)
  154. print(len(Foods))
  155. self.create_node('Check', Checks)
  156. print(len(Checks))
  157. self.create_node('Department', Departments)
  158. print(len(Departments))
  159. self.create_node('Producer', Producers)
  160. print(len(Producers))
  161. self.create_node('Symptom', Symptoms)
  162. return
  163. '''创建实体关系边'''
  164. def create_graphrels(self):
  165. Drugs, Foods, Checks, Departments, Producers, Symptoms, Diseases, disease_infos, rels_check, rels_recommandeat, rels_noteat, rels_doeat, rels_department, rels_commonddrug, rels_drug_producer, rels_recommanddrug,rels_symptom, rels_acompany, rels_category = self.read_nodes()
  166. self.create_relationship('Disease', 'Food', rels_recommandeat, 'recommand_eat', '推荐食谱')
  167. self.create_relationship('Disease', 'Food', rels_noteat, 'no_eat', '忌吃')
  168. self.create_relationship('Disease', 'Food', rels_doeat, 'do_eat', '宜吃')
  169. self.create_relationship('Department', 'Department', rels_department, 'belongs_to', '属于')
  170. self.create_relationship('Disease', 'Drug', rels_commonddrug, 'common_drug', '常用药品')
  171. self.create_relationship('Producer', 'Drug', rels_drug_producer, 'drugs_of', '生产药品')
  172. self.create_relationship('Disease', 'Drug', rels_recommanddrug, 'recommand_drug', '好评药品')
  173. self.create_relationship('Disease', 'Check', rels_check, 'need_check', '诊断检查')
  174. self.create_relationship('Disease', 'Symptom', rels_symptom, 'has_symptom', '症状')
  175. self.create_relationship('Disease', 'Disease', rels_acompany, 'acompany_with', '并发症')
  176. self.create_relationship('Disease', 'Department', rels_category, 'belongs_to', '所属科室')
  177. '''创建实体关联边'''
  178. def create_relationship(self, start_node, end_node, edges, rel_type, rel_name):
  179. count = 0
  180. # 去重处理
  181. set_edges = []
  182. for edge in edges:
  183. set_edges.append('###'.join(edge))
  184. all = len(set(set_edges))
  185. for edge in set(set_edges):
  186. edge = edge.split('###')
  187. p = edge[0]
  188. q = edge[1]
  189. query = "match(p:%s),(q:%s) where p.name='%s'and q.name='%s' create (p)-[rel:%s{name:'%s'}]->(q)" % (
  190. start_node, end_node, p, q, rel_type, rel_name)
  191. try:
  192. self.g.run(query)
  193. count += 1
  194. print(rel_type, count, all)
  195. except Exception as e:
  196. print(e)
  197. return
  198. '''导出数据'''
  199. def export_data(self):
  200. Drugs, Foods, Checks, Departments, Producers, Symptoms, Diseases, disease_infos, rels_check, rels_recommandeat, rels_noteat, rels_doeat, rels_department, rels_commonddrug, rels_drug_producer, rels_recommanddrug, rels_symptom, rels_acompany, rels_category = self.read_nodes()
  201. f_drug = open('drug.txt', 'w+')
  202. f_food = open('food.txt', 'w+')
  203. f_check = open('check.txt', 'w+')
  204. f_department = open('department.txt', 'w+')
  205. f_producer = open('producer.txt', 'w+')
  206. f_symptom = open('symptoms.txt', 'w+')
  207. f_disease = open('disease.txt', 'w+')
  208. f_drug.write('\n'.join(list(Drugs)))
  209. f_food.write('\n'.join(list(Foods)))
  210. f_check.write('\n'.join(list(Checks)))
  211. f_department.write('\n'.join(list(Departments)))
  212. f_producer.write('\n'.join(list(Producers)))
  213. f_symptom.write('\n'.join(list(Symptoms)))
  214. f_disease.write('\n'.join(list(Diseases)))
  215. f_drug.close()
  216. f_food.close()
  217. f_check.close()
  218. f_department.close()
  219. f_producer.close()
  220. f_symptom.close()
  221. f_disease.close()
  222. return
  223. if __name__ == '__main__':
  224. handler = MedicalGraph()
  225. # handler.export_data()
  226. handler.create_graphnodes()
  227. handler.create_graphrels()

代码参考刘焕勇老师的项目,连接如下,Author: lhy<lhy_in_blcu@126.com,https://huangyong.github.io>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/459799
推荐阅读
相关标签
  

闽ICP备14008679号