“基于医疗知识图谱的问答系统”代码解析(一)

“基于医疗知识图谱的问答系统”代码解析(一)

build_medicalgraph.py —建立医疗知识图谱的代码解析

“基于医疗知识图谱的问答系统”代码解析(二)
“基于医疗知识图谱的问答系统”代码解析(三)
“基于医疗知识图谱的问答系统”代码解析(四)
基于医疗知识图谱的问答系统”代码解析(五)

这是我对刘老师所写“基于知识医疗图谱的问答系统”代码的解读。

# 预备知识#!/usr/bin/env python3
# coding: utf-8
# File: MedicalGraph.py
# Author:lhy
# Date: 18-10-

# 构建知识图谱 并将知识图谱放入neo4j
import os
import json
# 为了从neo4j导入知识图谱

from py2neo import Graph,Node

class MedicalGraph:
    def __init__(self):
        # cur_dir 当前目录 即QASystemOnMedicalKG-master
        cur_dir = '/'.join(os.path.abspath(__file__).split('/')[:-1])

        self.data_path = os.path.join(cur_dir, 'data/medical.json')
        self.g = Graph(
            host="127.0.0.1",  # neo4j 搭载服务器的ip地址,ifconfig可获取到
            http_port=7474,    # neo4j 服务器监听的端口号
            user="neo4j",      # 数据库user name,如果没有更改过,应该是neo4j
            password="neo")    # passward第一次登入是neo4j,随后即更改密码

    '''读取文件'''
    def read_nodes(self):
        # 共7类节点 初始化为列表
        drugs = []     # 药品
        foods = []     # 食物
        checks = []    # 检查
        departments = []   # 科室
        producers = []     # 药品大类
        diseases = []      # 疾病
        symptoms = []      # 症状

        disease_infos = [] # 疾病信息

        # 构建节点实体关系
        rels_department = []     # 科室-科室关系
        rels_noteat = []         # 疾病-忌吃食物关系
        rels_doeat = []          # 疾病-宜吃食物关系
        rels_recommandeat = []   # 疾病-推荐吃食物关系
        rels_commonddrug = []    # 疾病-通用药品关系
        rels_recommanddrug = []  # 疾病-热门药品关系
        rels_check = []          # 疾病-检查关系
        rels_drug_producer = []  # 厂商-药物关系

        rels_symptom = [] # 疾病症状关系
        rels_acompany = [] # 疾病并发关系
        rels_category = [] # 疾病与科室之间的关系


        count = 0
        for data in open(self.data_path, encoding='utf-8'):
            # 疾病字典
            disease_dict = {}
            # 统计疾病数量
            count += 1
            # 输出统计
            print(count)
            data_json = json.loads(data)
            disease = data_json['name']
            disease_dict['name'] = disease
            diseases.append(disease)
            # 初始化键值对  其值都为字符串
            disease_dict['desc'] = ''
            disease_dict['prevent'] = ''
            disease_dict['cause'] = ''
            disease_dict['easy_get'] = ''
            disease_dict['cure_department'] = ''
            disease_dict['cure_way'] = ''
            disease_dict['cure_lasttime'] = ''
            disease_dict['symptom'] = ''
            disease_dict['cured_prob'] = ''

         # 更新关系表
            # 如果症状在文件里
            if 'symptom' in data_json:
                # 症状列表更新
                symptoms += data_json['symptom']

                # 遍历该病的症状表
                for symptom in data_json['symptom']:
                    # 添加疾病和症状的关系
                    rels_symptom.append([disease, symptom])

            # 疾病并发关系
            if 'acompany' in data_json:
                for acompany in data_json['acompany']:
                    # 添加疾病和并发的关系
                    rels_acompany.append([disease, acompany])

            # 更新字典
            if 'desc' in data_json:
                disease_dict['desc'] = data_json['desc']

            if 'prevent' in data_json:
                disease_dict['prevent'] = data_json['prevent']

            if 'cause' in data_json:
                disease_dict['cause'] = data_json['cause']

            if 'get_prob' in data_json:
                disease_dict['get_prob'] = data_json['get_prob']

            if 'easy_get' in data_json:
                disease_dict['easy_get'] = data_json['easy_get']

            # 部门
            if 'cure_department' in data_json:
                cure_department = data_json['cure_department']
                # 如果只涉及到1个部门 只添加与这一个部门的关系
                if len(cure_department) == 1:
                     rels_category.append([disease, cure_department[0]])

                # 如果涉及到2个部门 则把第一个作为大部门
                if len(cure_department) == 2:
                    big = cure_department[0]
                    small = cure_department[1]
                    rels_department.append([small, big])
                    rels_category.append([disease, small])

                # 更新疾病表格
                disease_dict['cure_department'] = cure_department
                departments += cure_department

            if 'cure_way' in data_json:
                disease_dict['cure_way'] = data_json['cure_way']

            if  'cure_lasttime' in data_json:
                disease_dict['cure_lasttime'] = data_json['cure_lasttime']

            if 'cured_prob' in data_json:
                disease_dict['cured_prob'] = data_json['cured_prob']

            if 'common_drug' in data_json:
                common_drug = data_json['common_drug']
                for drug in common_drug:
                    # 添加每个常规药与疾病的关系
                    rels_commonddrug.append([disease, drug])
                drugs += common_drug

            if 'recommand_drug' in data_json:
                recommand_drug = data_json['recommand_drug']
                drugs += recommand_drug
                for drug in recommand_drug:
                    # 添加每个热门药与疾病的关系
                    rels_recommanddrug.append([disease, drug])

            # 如果有忌口就更新以下数据(忌口,宜吃,推荐吃)
            if 'not_eat' in data_json:
                not_eat = data_json['not_eat']
                for _not in not_eat:
                    # 添加疾病与忌口的关系
                    rels_noteat.append([disease, _not])
                foods += not_eat
                do_eat = data_json['do_eat']
                for _do in do_eat:
                    # 添加疾病与宜吃食物的关系
                    rels_doeat.append([disease, _do])
                foods += do_eat
                # 更新推荐表
                recommand_eat = data_json['recommand_eat']
                for _recommand in recommand_eat:
                    # 添加疾病和推荐食物的关系
                    rels_recommandeat.append([disease, _recommand])
                foods += recommand_eat
            # 更新检查
            if 'check' in data_json:
                check = data_json['check']
                for _check in check:
                    # 添加疾病与检查之前的关系
                    rels_check.append([disease, _check])
                checks += check
            # 更新药店信息
            if 'drug_detail' in data_json:
                drug_detail = data_json['drug_detail']
                # drug_detail  举例易理解
                # 假设"drug_detail" :[ "桂林南药布美他尼片(布美他尼片)","皇隆制药注射用呋塞米(注射用呋塞米)" ]
                #  输出为  注意这里的[0]是从前面开始 [-1]是从后面开始的
                # ['桂林南药布美他尼片', '皇隆制药注射用呋塞米']
                # [['桂林南药布美他尼片', '布美他尼片'], ['皇隆制药注射用呋塞米', '注射用呋塞米']]
                producer = [i.split('(')[0] for i in drug_detail]
                rels_drug_producer += [[i.split('(')[0], i.split('(')[-1].replace(')', '')] for i in drug_detail]
                producers += producer
            disease_infos.append(disease_dict)
        # 返回数据 set()=>强制转化为集合
        return set(drugs), set(foods), set(checks), set(departments), set(producers), set(symptoms), set(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

    '''建立节点'''
    def create_node(self, label, nodes):
        # 传入标签,后面会设置
        # node计数单位
        count = 0
        for node_name in nodes:
            node = Node(label, name=node_name)
            self.g.create(node)
            count += 1
            print(count, len(nodes))
        return

    '''创建知识图谱中心疾病的节点'''
    def create_diseases_nodes(self, disease_infos):
        # diseasesnode计数单位
        count = 0
        for disease_dict in disease_infos:
            node = Node("Disease", name=disease_dict['name'], desc=disease_dict['desc'],
                        prevent=disease_dict['prevent'] ,cause=disease_dict['cause'],
                        easy_get=disease_dict['easy_get'],cure_lasttime=disease_dict['cure_lasttime'],
                        cure_department=disease_dict['cure_department']
                        ,cure_way=disease_dict['cure_way'] , cured_prob=disease_dict['cured_prob'])
            self.g.create(node)
            count += 1
            print(count)
        return

    '''创建知识图谱实体节点类型schema'''
    def create_graphnodes(self):
        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()
        self.create_diseases_nodes(disease_infos)
        self.create_node('Drug', Drugs)
        print(len(Drugs))
        self.create_node('Food', Foods)
        print(len(Foods))
        self.create_node('Check', Checks)
        print(len(Checks))
        self.create_node('Department', Departments)
        print(len(Departments))
        self.create_node('Producer', Producers)
        print(len(Producers))
        self.create_node('Symptom', Symptoms)
        return


    '''创建实体关系边'''
    def create_graphrels(self):
        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()
        # Food是大类
        self.create_relationship('Disease', 'Food', rels_recommandeat, 'recommand_eat', '推荐食谱')
        self.create_relationship('Disease', 'Food', rels_noteat, 'no_eat', '忌吃')
        self.create_relationship('Disease', 'Food', rels_doeat, 'do_eat', '宜吃')
        self.create_relationship('Department', 'Department', rels_department, 'belongs_to', '属于')
        self.create_relationship('Disease', 'Drug', rels_commonddrug, 'common_drug', '常用药品')
        self.create_relationship('Producer', 'Drug', rels_drug_producer, 'drugs_of', '生产药品')
        self.create_relationship('Disease', 'Drug', rels_recommanddrug, 'recommand_drug', '好评药品')
        self.create_relationship('Disease', 'Check', rels_check, 'need_check', '诊断检查')
        self.create_relationship('Disease', 'Symptom', rels_symptom, 'has_symptom', '症状')
        self.create_relationship('Disease', 'Disease', rels_acompany, 'acompany_with', '并发症')
        self.create_relationship('Disease', 'Department', rels_category, 'belongs_to', '所属科室')

    '''创建实体关联边'''
    def create_relationship(self, start_node, end_node, edges, rel_type, rel_name):
        count = 0
        # 去重处理
        set_edges = []
        for edge in edges:
            # 将每对元素以 ### 分割 并添加到set_edges
            set_edges.append('###'.join(edge))
        all = len(set(set_edges))
        for edge in set(set_edges):
            # 遍历每对元素
            edge = edge.split('###')
            p = edge[0]
            q = edge[1]
            # Cypher语言 Match 类似与SQL中的Select,用来匹配一种搜索模式 匹配p与q
            query = "match(p:%s),(q:%s) where p.name='%s'and q.name='%s' create (p)-[rel:%s{name:'%s'}]->(q)" % (
                start_node, end_node, p, q, rel_type, rel_name)
            try:
                self.g.run(query)
                count += 1
                print(rel_type, count, all)
            except Exception as e:
                print(e)
        return

    '''导出数据'''
    def export_data(self):
        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()
        # 将数据写到文件
        f_drug = open('drug.txt', 'w+')
        f_food = open('food.txt', 'w+')
        f_check = open('check.txt', 'w+')
        f_department = open('department.txt', 'w+')
        f_producer = open('producer.txt', 'w+')
        f_symptom = open('symptoms.txt', 'w+')
        f_disease = open('disease.txt', 'w+')

        # \n为分割
        f_drug.write('\n'.join(list(Drugs)))
        f_food.write('\n'.join(list(Foods)))
        f_check.write('\n'.join(list(Checks)))
        f_department.write('\n'.join(list(Departments)))
        f_producer.write('\n'.join(list(Producers)))
        f_symptom.write('\n'.join(list(Symptoms)))
        f_disease.write('\n'.join(list(Diseases)))

        # 关闭文件
        f_drug.close()
        f_food.close()
        f_check.close()
        f_department.close()
        f_producer.close()
        f_symptom.close()
        f_disease.close()

        return

if __name__ == '__main__':
    handler = MedicalGraph()
    print("step1:导入图谱节点中")
    handler.create_graphnodes()
    print("step2:导入图谱边中")      
    handler.create_graphrels()   

成功构建后的知识图谱

“基于医疗知识图谱的问答系统”代码解析(一)_第1张图片
“基于医疗知识图谱的问答系统”代码解析(一)_第2张图片

总结

注释有的简单就不写在上面了,欢迎指出不足。
当然代码很重要,但是之前的准备也要做好,比如neo4j的配置,因为我也是初入知识图谱,对这方面不太熟悉,就想着去github网找一个代码跑一下,结果经过了两天时间,我才跑成功,可能是我太笨了,不过笨鸟先飞。neo4j的配置 我就弄了挺久,所以推荐下面的链接给各位看官,希望各位看官多多支持,有疑惑随时提出,https://www.it610.com/article/1289837419532722176.htm

后续我会不断更新,希望各位看官多多指点

你可能感兴趣的:(知识图谱问答,python,neo4j,知识图谱)