赞
踩
原项目地址:新建标签页 (github.com)
实体规模4.4万,实体关系规模30万。
MongoDB-Windows-x86_64
mongodb-compass-1.36.1-win32-x64(安装的时候注意安装路径最好不要出现中文,不然会很麻烦)
neo4j-community-4.2.4-windows(这里我是去找了4开头的历史版本)
jdk-11.0.18_windows-x64_bin
开始项目时MongoDB、neo4j全程打开
连接MongoDB
(1)打开cmd,进入E:\mongodb\bin目录下,输入命令“mongod --dbpath E:\mongodb\data”即可开启MongoDB服务。
(2)浏览器进入http://127.0.0.1:27017,显示“It looks like you are trying to access MongoDB over HTTP on the native driver port.”则表示连接成功。
连接neo4j
(1)进入E:\知识图谱\neo4j\neo4j-community-4.2.4\bin,输入neo4j.bat console。
(2)浏览器进入http://localhost:7474/browser/。
1.data_spider.py 爬取数据(数据的原网站是寻医问药网的疾病百科)
import urllib.request import urllib.parse from lxml import etree import pymongo import re class CrimeSpider: def __init__(self): self.conn = pymongo.MongoClient()#创建数据库连接 self.db = self.conn['medical']#获取数据库‘medical' self.col = self.db['data']#获取文件'data' #根据url,请求html def get_html(self, url): headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/51.0.2704.63 Safari/537.36'}#UA使得服务器能够识别客户使用的操作系统及版本、CPU类型、浏览器及版本等,这里是要程序伪装成浏览器进行访问 req = urllib.request.Request(url=url, headers=headers)#发起带header头的请求 res = urllib.request.urlopen(req)#返回一个object对象 html = res.read().decode('gbk')#想要获取内容还需要进一步的解析 return html def url_parser(self, content): selector = etree.HTML(content)#将content转化为能被xpath匹配的格式 urls = ['http://jib.xywy.com' + i for i in selector.xpath('//h2[@class="item-title"]/a/@href')]#抓取所有病例的页面 return urls #将内容写入数据库 def spider_main(self): for page in range(1, 11000): try: basic_url = 'http://jib.xywy.com/il_sii/gaishu/%s.htm'%page#疾病概述页面 cause_url = 'http://jib.xywy.com/il_sii/cause/%s.htm'%page#病因页面 prevent_url = 'http://jib.xywy.com/il_sii/prevent/%s.htm'%page#预防页面 symptom_url = 'http://jib.xywy.com/il_sii/symptom/%s.htm'%page#症状页面 inspect_url = 'http://jib.xywy.com/il_sii/inspect/%s.htm'%page#检查方法页面 treat_url = 'http://jib.xywy.com/il_sii/treat/%s.htm'%page#治疗页面 food_url = 'http://jib.xywy.com/il_sii/food/%s.htm'%page#食物页面 drug_url = 'http://jib.xywy.com/il_sii/drug/%s.htm'%page#药品页面 data = {}#将以下数据封装成字典 data['url'] = basic_url#基本网址 data['basic_info'] = self.basicinfo_spider(basic_url)#疾病基本信息。字典。'basic_info':{'category':疾病分类,'name':疾病名称,'desc':疾病简介,'attributes':[基本知识,治疗常识,温馨提示]} data['cause_info'] = self.common_spider(cause_url)#病因。list。'cause_info':[第一段文字,第二段文字,...] data['prevent_info'] = self.common_spider(prevent_url)#预防。list。'prevent_info':[第一段文字,第二段文字,...] data['symptom_info'] = self.symptom_spider(symptom_url)#症状(应该是并发症)。元组。'symptom_info':(症状信息,[第一段症状,第二段症状,...]) data['inspect_info'] = self.inspect_spider(inspect_url)#检查方法的网址。list。'inspect_info':[检查方法网址,.....] data['treat_info'] = self.treat_spider(treat_url)#治疗概述。list。 'treat_info':[就诊科室,治疗方式,治疗周期,治愈率,常用药品] data['food_info'] = self.food_spider(food_url)#食物,字典。'food_info':{'good':宜吃食物, 'bad':忌食物, 'recommand':宜食物推荐食物} data['drug_info'] = self.drug_spider(drug_url)#药品名称。str。'drug_info':药品名称 print(page, basic_url)#打印出 self.col.insert(data)#将上述数据封装成的字典,写入数据库 except Exception as e: print(e, page) return #基本信息解析 def basicinfo_spider(self, url): html = self.get_html(url) selector = etree.HTML(html) title = selector.xpath('//title/text()')[0]#网页的标题,使用正则表达式提取内容中的某部分 category = selector.xpath('//div[@class="wrap mt10 nav-bar"]/a/text()')#分类 desc = selector.xpath('//div[@class="jib-articl-con jib-lh-articl"]/p/text()')#简介 ps = selector.xpath('//div[@class="mt20 articl-know"]/p')#[基本知识,治疗常识,温馨提示] infobox = [] for p in ps: info = p.xpath('string(.)').replace('\r','').replace('\n','').replace('\xa0', '').replace(' ', '').replace('\t','')#清理换行符等内容 infobox.append(info) basic_data = {} basic_data['category'] = category basic_data['name'] = title.split('的简介')[0] basic_data['desc'] = desc basic_data['attributes'] = infobox return basic_data #treat_infobox治疗解析 def treat_spider(self, url): html = self.get_html(url) selector = etree.HTML(html) ps = selector.xpath('//div[starts-with(@class,"mt20 articl-know")]/p') infobox = [] for p in ps: info = p.xpath('string(.)').replace('\r','').replace('\n','').replace('\xa0', '').replace(' ', '').replace('\t','') infobox.append(info) return infobox #treat_infobox治疗解析 def drug_spider(self, url): html = self.get_html(url) selector = etree.HTML(html) drugs = [i.replace('\n','').replace('\t', '').replace(' ','') for i in selector.xpath('//div[@class="fl drug-pic-rec mr30"]/p/a/text()')] return drugs #food治疗解析 def food_spider(self, url): html = self.get_html(url) selector = etree.HTML(html) divs = selector.xpath('//div[@class="diet-img clearfix mt20"]') try:#异常处理 food_data = {} food_data['good'] = divs[0].xpath('./div/p/text()') food_data['bad'] = divs[1].xpath('./div/p/text()') food_data['recommand'] = divs[2].xpath('./div/p/text()') except: return {} return food_data #症状信息解析 def symptom_spider(self, url): html = self.get_html(url) selector = etree.HTML(html) symptoms = selector.xpath('//a[@class="gre" ]/text()') ps = selector.xpath('//p') detail = [] for p in ps: info = p.xpath('string(.)').replace('\r','').replace('\n','').replace('\xa0', '').replace(' ', '').replace('\t','') detail.append(info) symptoms_data = {} symptoms_data['symptoms'] = symptoms symptoms_data['symptoms_detail'] = detail return symptoms, detail #检查信息解析 def inspect_spider(self, url): html = self.get_html(url) selector = etree.HTML(html) inspects = selector.xpath('//li[@class="check-item"]/a/@href') return inspects #通用解析模块 def common_spider(self, url): html = self.get_html(url) selector = etree.HTML(html) ps = selector.xpath('//p') infobox = [] for p in ps: info = p.xpath('string(.)').replace('\r', '').replace('\n', '').replace('\xa0', '').replace(' ','').replace('\t', '') if info: infobox.append(info) return '\n'.join(infobox) #检查项抓取模块 def inspect_crawl(self): for page in range(1, 3685): try: url = 'http://jck.xywy.com/jc_%s.html'%page html = self.get_html(url) data = {}#检查的字典数据 data['url']= url#检查项目网页的网址 data['html'] = html#检查项目网页的源码 self.db['jc'].insert(data)#放到jc这个数据库里 print(url) except Exception as e: print(e) handler = CrimeSpider() handler.inspect_crawl() handler.spider_main()
2.max_cut.py 基于词典的最大前向/后向匹配。
class CutWords: def __init__(self): dict_path = './disease.txt'#加载保存疾病名称的文档 self.word_dict, self.max_wordlen = self.load_words(dict_path) #加载词典 def load_words(self, dict_path): words = list()#list()方法用于将元组或字符串转换为列表,所以这里是想要构建一个空列表。然后定义最大字长变量,在字典遍历的过程中,不断将疾病名称保存到words中,同时更新最大字长。 max_len = 0 for line in open(dict_path): wd = line.strip() if not wd: continue if len(wd) > max_len: max_len = len(wd) words.append(wd) return words, max_len #最大向前匹配 def max_forward_cut(self, sent): # 1.从左向右取待切分汉语句的m个字符作为匹配字段,m为大机器词典中最长词条个数。 # 2.查找大机器词典并进行匹配。若匹配成功,则将这个匹配字段作为一个词切分出来。如果没有则字长减一继续匹配,直到匹配到为止,如果到最后也没有匹配成功的话,就返回该字段第一个值。 cutlist = [] index = 0 while index < len(sent): matched = False for i in range(self.max_wordlen, 0, -1): cand_word = sent[index: index + i] if cand_word in self.word_dict: cutlist.append(cand_word) matched = True break # 如果没有匹配上,则按字符切分 if not matched: i = 1 cutlist.append(sent[index]) index += i return cutlist # 最大向后匹配 def max_backward_cut(self, sent): # 1.从右向左取待切分汉语句的m个字符作为匹配字段,m为大机器词典中最长词条个数。 # 2.查找大机器词典并进行匹配。若匹配成功,则将这个匹配字段作为一个词切分出来。和前面的最大向前匹配类似,只不过在该函数中如果最后匹配失败则返回字段最后一个值。 cutlist = [] index = len(sent) max_wordlen = 5 while index > 0: matched = False for i in range(self.max_wordlen, 0, -1): tmp = (i + 1) cand_word = sent[index - tmp: index] # 如果匹配上,则将字典中的字符加入到切分字符中 if cand_word in self.word_dict: cutlist.append(cand_word) matched = True break # 如果没有匹配上,则按字符切分 if not matched: tmp = 1 cutlist.append(sent[index - 1]) index -= tmp return cutlist[::-1] # 双向最大向前匹配 def max_biward_cut(self, sent): # 双向最大匹配法是将正向最大匹配法得到的分词结果和逆向最大匹配法的到的结果进行比较,从而决定正确的分词方法。 # 启发式规则: # 1.如果正反向分词结果词数不同,则取分词数量较少的那个。 # 2.如果分词结果词数相同 a.分词结果相同,就说明没有歧义,可返回任意一个。 b.分词结果不同,返回其中单字较少的那个。 forward_cutlist = self.max_forward_cut(sent) backward_cutlist = self.max_backward_cut(sent) count_forward = len(forward_cutlist) count_backward = len(backward_cutlist) def compute_single(word_list): num = 0 for word in word_list: if len(word) == 1: num += 1 return num if count_forward == count_backward: if compute_single(forward_cutlist) > compute_single(backward_cutlist): return backward_cutlist else: return forward_cutlist elif count_backward > count_forward: return forward_cutlist else: return backward_cutlist
3.build_data.py 将爬虫爬取的数据进行规整
import pymongo from lxml import etree import os from max_cut import * class MedicalGraph: def __init__(self): self.conn = pymongo.MongoClient()#建立无用户密码连接 cur_dir = '/'.join(os.path.abspath(__file__).split('/')[:-1])#当前文件夹地址 self.db = self.conn['medical'] self.col = self.db['data'] first_words = [i.strip() for i in open(os.path.join(cur_dir, 'first_name.txt'))] alphabets = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y', 'z'] nums = ['1','2','3','4','5','6','7','8','9','0'] self.stop_words = first_words + alphabets + nums self.key_dict = { '医保疾病' : 'yibao_status', "患病比例" : "get_prob", "易感人群" : "easy_get", "传染方式" : "get_way", "就诊科室" : "cure_department", "治疗方式" : "cure_way", "治疗周期" : "cure_lasttime", "治愈率" : "cured_prob", '药品明细': 'drug_detail', '药品推荐': 'recommand_drug', '推荐': 'recommand_eat', '忌食': 'not_eat', '宜食': 'do_eat', '症状': 'symptom', '检查': 'check', '成因': 'cause', '预防措施': 'prevent', '所属类别': 'category', '简介': 'desc', '名称': 'name', '常用药品' : 'common_drug', '治疗费用': 'cost_money', '并发症': 'acompany' } self.cuter = CutWords()#创建最大前向/后向匹配类的实例 def collect_medical(self): cates = [] inspects = [] count = 0 for item in self.col.find(): data = {} basic_info = item['basic_info']#遍历 name = basic_info['name'] if not name: continue # 基本信息 data['名称'] = name data['简介'] = '\n'.join(basic_info['desc']).replace('\r\n\t', '').replace('\r\n\n\n','').replace(' ','').replace('\r\n','\n') category = basic_info['category'] data['所属类别'] = category cates += category inspect = item['inspect_info'] inspects += inspect attributes = basic_info['attributes'] # 成因及预防 data['预防措施'] = item['prevent_info'] data['成因'] = item['cause_info'] # 并发症 data['症状'] = list(set([i for i in item["symptom_info"][0] if i[0] not in self.stop_words])) for attr in attributes: attr_pair = attr.split(':') if len(attr_pair) == 2: key = attr_pair[0] value = attr_pair[1] data[key] = value # 检查 inspects = item['inspect_info'] jcs = [] for inspect in inspects: jc_name = self.get_inspect(inspect) if jc_name: jcs.append(jc_name) data['检查'] = jcs # 食物 food_info = item['food_info'] if food_info: data['宜食'] = food_info['good'] data['忌食'] = food_info['bad'] data['推荐'] = food_info['recommand'] # 药品 drug_info = item['drug_info'] data['药品推荐'] = list(set([i.split('(')[-1].replace(')','') for i in drug_info])) data['药品明细'] = drug_info data_modify = {} for attr, value in data.items(): attr_en = self.key_dict.get(attr)#'name' if attr_en: data_modify[attr_en] = value#把内容放到data里面,如 'name':白百咳 if attr_en in ['yibao_status', 'get_prob', 'easy_get', 'get_way', "cure_lasttime", "cured_prob"]: data_modify[attr_en] = value.replace(' ','').replace('\t','') elif attr_en in ['cure_department', 'cure_way', 'common_drug']: data_modify[attr_en] = [i for i in value.split(' ') if i] elif attr_en in ['acompany']: acompany = [i for i in self.cuter.max_biward_cut(data_modify[attr_en]) if len(i) > 1] data_modify[attr_en] = acompany try: self.db['medical'].insert(data_modify)#插入字典 count += 1 print(count) except Exception as e: print(e) return def get_inspect(self, url): res = self.db['jc'].find_one({'url':url}) if not res: return '' else: return res['name'] def modify_jc(self): for item in self.db['jc'].find(): url = item['url'] content = item['html'] selector = etree.HTML(content) name = selector.xpath('//title/text()')[0].split('结果分析')[0] desc = selector.xpath('//meta[@name="description"]/@content')[0].replace('\r\n\t','') self.db['jc'].update({'url':url}, {'$set':{'name':name, 'desc':desc}}) if __name__ == '__main__': handler = MedicalGraph() handler.modify_jc() handler.collect_medical()
运行build_medicalgraph.py 将结构化JSON数据导入neo4j
在PyCharm终端安装py2neo:pip install py2neo==4.3.0 -i https://pypi.douban.com/simple
(1)知识图谱实体类型
(2)知识图谱实体关系类型
(3)知识图谱属性类型
(4)支持问答的类型
import os import json from py2neo import Graph,Node class MedicalGraph: def __init__(self): cur_dir = '/'.join(os.path.abspath(__file__).split('/')[:-1]) self.data_path = os.path.join(cur_dir, 'medical.json')#json地址 self.g = Graph('http://localhost:7474', auth = ('neo4j', '072766'))#连接数据库 #读取文件 def read_nodes(self): # 共7类节点 drugs = [] # 药品 foods = [] # 食物 checks = [] # 检查 departments = [] # 科室 producers = [] # 药品大类 diseases = [] # 疾病 symptoms = [] # 症状 disease_infos = []##疾病信息,里面是字典格式[{'name':...,'desc':...,...,...},{}],里面是所有的实体节点 # 构建节点实体关系 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'] if len(cure_department) == 1: rels_category.append([disease, cure_department[0]]) 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#然后将其保存到disease_dict字典和departments列表中 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'] 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)#最后将建立好的该疾病字典保存到disease_infos列表当中 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): count = 0 for node_name in nodes:#新建节点,每个节点有一个name属性 node = Node(label, name=node_name) self.g.create(node)#新建数据库节点 count += 1 print(count, len(nodes)) return #创建知识图谱中心疾病的节点 def create_diseases_nodes(self, disease_infos): 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)#为每一个疾病都创建了一个节点,每个节点有9个属性 self.create_node('Drug', Drugs)#为每个药品创建一个节点,有一个属性name = 药品名称 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() 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): # start_node是边的起点名称, end_node是边的终点如'Food', edges是边的关系(实际关联项) ,p是起始节点的名称,q是到达节点的名称,rel_type是关系的类型,具体字段如‘do_eat’;rel_name是关系的名称,具体字段如‘宜吃’ count = 0 # 去重处理,实体关系为形如[[“a”,“b”],[“c”,“d”]]的嵌套list,无法直接用set去重,所以先将嵌套内层的list转为字符串,再用set set_edges = [] for edge in 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] 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)#run()的用法大概是这样的,比如start_node, end_node这两种节点已经提前存进去了,比如label分别是Disease和Food,现在需要在他们间建立关系,括号里面是neo4j的查询语句cql,语法结构类似sql语句。关系就是rel_typ,还带了一个属性{name:'rel_name'} 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+') 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()
question_classifier.py
import os import ahocorasick#ahocorasick实现快速的关键字匹配 class QuestionClassifier: def __init__(self): cur_dir = '/'.join(os.path.abspath(__file__).split('/')[:-1]) # 特征词路径 self.disease_path = os.path.join(cur_dir, 'disease.txt') self.department_path = os.path.join(cur_dir, 'department.txt') self.check_path = os.path.join(cur_dir, 'check.txt') self.drug_path = os.path.join(cur_dir, 'drug.txt') self.food_path = os.path.join(cur_dir, 'food.txt') self.producer_path = os.path.join(cur_dir, 'producer.txt') self.symptom_path = os.path.join(cur_dir, 'symptom.txt') self.deny_path = os.path.join(cur_dir, 'deny.txt') # 加载特征词 self.disease_wds= [i.strip() for i in open(self.disease_path,encoding='utf-8') if i.strip()] self.department_wds= [i.strip() for i in open(self.department_path,encoding='utf-8') if i.strip()] self.check_wds= [i.strip() for i in open(self.check_path,encoding='utf-8') if i.strip()] self.drug_wds= [i.strip() for i in open(self.drug_path,encoding='utf-8') if i.strip()] self.food_wds= [i.strip() for i in open(self.food_path,encoding='utf-8') if i.strip()] self.producer_wds= [i.strip() for i in open(self.producer_path,encoding='utf-8') if i.strip()] self.symptom_wds= [i.strip() for i in open(self.symptom_path,encoding='utf-8') if i.strip()] self.region_words = set(self.department_wds + self.disease_wds + self.check_wds + self.drug_wds + self.food_wds + self.producer_wds + self.symptom_wds) self.deny_words = [i.strip() for i in open(self.deny_path,encoding='utf-8') if i.strip()] # 构造领域actree self.region_tree = self.build_actree(list(self.region_words)) # 构建词典 self.wdtype_dict = self.build_wdtype_dict()#词的类型的字典,{'百日咳':'disease',....} # 问句疑问词 self.symptom_qwds = ['症状', '表征', '现象', '症候', '表现'] self.cause_qwds = ['原因','成因', '为什么', '怎么会', '怎样才', '咋样才', '怎样会', '如何会', '为啥', '为何', '如何才会', '怎么才会', '会导致', '会造成'] self.acompany_qwds = ['并发症', '并发', '一起发生', '一并发生', '一起出现', '一并出现', '一同发生', '一同出现', '伴随发生', '伴随', '共现'] self.food_qwds = ['饮食', '饮用', '吃', '食', '伙食', '膳食', '喝', '菜' ,'忌口', '补品', '保健品', '食谱', '菜谱', '食用', '食物','补品'] self.drug_qwds = ['药', '药品', '用药', '胶囊', '口服液', '炎片'] self.prevent_qwds = ['预防', '防范', '抵制', '抵御', '防止','躲避','逃避','避开','免得','逃开','避开','避掉','躲开','躲掉','绕开', '怎样才能不', '怎么才能不', '咋样才能不','咋才能不', '如何才能不', '怎样才不', '怎么才不', '咋样才不','咋才不', '如何才不', '怎样才可以不', '怎么才可以不', '咋样才可以不', '咋才可以不', '如何可以不', '怎样才可不', '怎么才可不', '咋样才可不', '咋才可不', '如何可不'] self.lasttime_qwds = ['周期', '多久', '多长时间', '多少时间', '几天', '几年', '多少天', '多少小时', '几个小时', '多少年'] self.cureway_qwds = ['怎么治疗', '如何医治', '怎么医治', '怎么治', '怎么医', '如何治', '医治方式', '疗法', '咋治', '怎么办', '咋办', '咋治'] self.cureprob_qwds = ['多大概率能治好', '多大几率能治好', '治好希望大么', '几率', '几成', '比例', '可能性', '能治', '可治', '可以治', '可以医'] self.easyget_qwds = ['易感人群', '容易感染', '易发人群', '什么人', '哪些人', '感染', '染上', '得上'] self.check_qwds = ['检查', '检查项目', '查出', '检查', '测出', '试出'] self.belong_qwds = ['属于什么科', '属于', '什么科', '科室'] self.cure_qwds = ['治疗什么', '治啥', '治疗啥', '医治啥', '治愈啥', '主治啥', '主治什么', '有什么用', '有何用', '用处', '用途', '有什么好处', '有什么益处', '有何益处', '用来', '用来做啥', '用来作甚', '需要', '要'] print('model init finished ......') return #分类主函数 def classify(self, question): data = {} medical_dict = self.check_medical(question)#从问句中匹配出的,{'百日咳':'disease',....} if not medical_dict: return {} data['args'] = medical_dict #收集问句当中所涉及到的实体类型 types = [] for type_ in medical_dict.values(): types += type_ question_type = 'others' question_types = [] # 症状 if self.check_words(self.symptom_qwds, question) and ('disease' in types): question_type = 'disease_symptom'#问句类型为:已知疾病询问症状 question_types.append(question_type) if self.check_words(self.symptom_qwds, question) and ('symptom' in types): question_type = 'symptom_disease'#已知症状问疾病 question_types.append(question_type) # 原因 if self.check_words(self.cause_qwds, question) and ('disease' in types): question_type = 'disease_cause' question_types.append(question_type) # 并发症 if self.check_words(self.acompany_qwds, question) and ('disease' in types): question_type = 'disease_acompany' question_types.append(question_type) # 推荐食品 if self.check_words(self.food_qwds, question) and 'disease' in types: deny_status = self.check_words(self.deny_words, question) if deny_status: question_type = 'disease_not_food' else: question_type = 'disease_do_food' question_types.append(question_type) #已知食物找疾病 if self.check_words(self.food_qwds+self.cure_qwds, question) and 'food' in types: deny_status = self.check_words(self.deny_words, question) if deny_status: question_type = 'food_not_disease' else: question_type = 'food_do_disease' question_types.append(question_type) # 推荐药品 if self.check_words(self.drug_qwds, question) and 'disease' in types: question_type = 'disease_drug' question_types.append(question_type) # 药品治啥病 if self.check_words(self.cure_qwds, question) and 'drug' in types: question_type = 'drug_disease' question_types.append(question_type) # 疾病接受检查项目 if self.check_words(self.check_qwds, question) and 'disease' in types: question_type = 'disease_check' question_types.append(question_type) # 已知检查项目查相应疾病 if self.check_words(self.check_qwds+self.cure_qwds, question) and 'check' in types: question_type = 'check_disease' question_types.append(question_type) # 症状防御 if self.check_words(self.prevent_qwds, question) and 'disease' in types: question_type = 'disease_prevent' question_types.append(question_type) # 疾病医疗周期 if self.check_words(self.lasttime_qwds, question) and 'disease' in types: question_type = 'disease_lasttime' question_types.append(question_type) # 疾病治疗方式 if self.check_words(self.cureway_qwds, question) and 'disease' in types: question_type = 'disease_cureway' question_types.append(question_type) # 疾病治愈可能性 if self.check_words(self.cureprob_qwds, question) and 'disease' in types: question_type = 'disease_cureprob' question_types.append(question_type) # 疾病易感染人群 if self.check_words(self.easyget_qwds, question) and 'disease' in types : question_type = 'disease_easyget' question_types.append(question_type) # 若没有查到相关的外部查询信息,那么则将该疾病的描述信息返回 if question_types == [] and 'disease' in types: question_types = ['disease_desc'] # 若没有查到相关的外部查询信息,那么则将该疾病的描述信息返回 if question_types == [] and 'symptom' in types: question_types = ['symptom_disease'] # 将多个分类结果进行合并处理,组装成一个字典 data['question_types'] = question_types return data #构造词对应的类型 def build_wdtype_dict(self): wd_dict = dict()#创建一个空字典 for wd in self.region_words:#所有的关键字 wd_dict[wd] = [] if wd in self.disease_wds:#如果该关键字属于 疾病,则wd_dict[wd] = ['disease'] wd_dict[wd].append('disease') if wd in self.department_wds: wd_dict[wd].append('department') if wd in self.check_wds: wd_dict[wd].append('check') if wd in self.drug_wds: wd_dict[wd].append('drug') if wd in self.food_wds: wd_dict[wd].append('food') if wd in self.symptom_wds: wd_dict[wd].append('symptom') if wd in self.producer_wds: wd_dict[wd].append('producer') return wd_dict#返回了一个字典,里面的内容是{'百日咳':'disease',....} #构造actree,加速过滤,输入list,输出一个AC树 def build_actree(self, wordlist): actree = ahocorasick.Automaton() for index, word in enumerate(wordlist): actree.add_word(word, (index, word)) actree.make_automaton() return actree #问句过滤 def check_medical(self, question): region_wds = [] for i in self.region_tree.iter(question): # 快速匹配,匹配的结果是一个双重元组序列,形如('百日咳',(3324,'百日咳')),就是前面的actree.add_word(word, (index, word))给加进来成tree的。这个index是在前面所有关键字加在一起之后的region_words中的序列号 wd = i[1][1]#把'百日咳'这个关键字给挑出来了 region_wds.append(wd)#把所有的关键字列入列表region_wds stop_wds = [] for wd1 in region_wds:#1.如果一个问句里面挑出了两个词 for wd2 in region_wds: if wd1 in wd2 and wd1 != wd2:#2.如果其中一个词包含另一个词 stop_wds.append(wd1)#3.则把短的词写入stop_wds final_wds = [i for i in region_wds if i not in stop_wds]#4.final_wds中是把region_wds去掉stop_wds。就是说如果问句中一个词包含另外一个词,则以长词为准。 final_dict = {i:self.wdtype_dict.get(i) for i in final_wds}#类似于{'百日咳':'disease',....},其中'百日咳'在问句中,且不在stop_wds中。 return final_dict #基于特征词进行分类 def check_words(self, wds, sent): for wd in wds: if wd in sent: return True return False if __name__ == '__main__': handler = QuestionClassifier() while 1: question = input('input an question:') data = handler.classify(question) print(data)
2.question_parser.py
class QuestionPaser: #构建实体节点 def build_entitydict(self, args): entity_dict = {} for arg, types in args.items(): for type in types: if type not in entity_dict: entity_dict[type] = [arg] else: entity_dict[type].append(arg) return entity_dict#构建一个字典,将所有同类型的实体放在一个值里,键是类型。如{'disease':['百日咳',...],....} #解析主函数 def parser_main(self, res_classify): args = res_classify['args']#{'百日咳':'disease',....} entity_dict = self.build_entitydict(args)#{'disease':['百日咳',...],....} question_types = res_classify['question_types']#问题类型 sqls = [] for question_type in question_types: sql_ = {} sql_['question_type'] = question_type sql = [] if question_type == 'disease_symptom': sql = self.sql_transfer(question_type, entity_dict.get('disease')) elif question_type == 'symptom_disease': sql = self.sql_transfer(question_type, entity_dict.get('symptom')) elif question_type == 'disease_cause': sql = self.sql_transfer(question_type, entity_dict.get('disease')) elif question_type == 'disease_acompany': sql = self.sql_transfer(question_type, entity_dict.get('disease')) elif question_type == 'disease_not_food': sql = self.sql_transfer(question_type, entity_dict.get('disease')) elif question_type == 'disease_do_food': sql = self.sql_transfer(question_type, entity_dict.get('disease')) elif question_type == 'food_not_disease': sql = self.sql_transfer(question_type, entity_dict.get('food')) elif question_type == 'food_do_disease': sql = self.sql_transfer(question_type, entity_dict.get('food')) elif question_type == 'disease_drug': sql = self.sql_transfer(question_type, entity_dict.get('disease')) elif question_type == 'drug_disease': sql = self.sql_transfer(question_type, entity_dict.get('drug')) elif question_type == 'disease_check': sql = self.sql_transfer(question_type, entity_dict.get('disease')) elif question_type == 'check_disease': sql = self.sql_transfer(question_type, entity_dict.get('check')) elif question_type == 'disease_prevent': sql = self.sql_transfer(question_type, entity_dict.get('disease')) elif question_type == 'disease_lasttime': sql = self.sql_transfer(question_type, entity_dict.get('disease')) elif question_type == 'disease_cureway': sql = self.sql_transfer(question_type, entity_dict.get('disease')) elif question_type == 'disease_cureprob': sql = self.sql_transfer(question_type, entity_dict.get('disease')) elif question_type == 'disease_easyget': sql = self.sql_transfer(question_type, entity_dict.get('disease')) elif question_type == 'disease_desc': sql = self.sql_transfer(question_type, entity_dict.get('disease')) if sql: sql_['sql'] = sql sqls.append(sql_) return sqls #针对不同的问题,分开进行处理 def sql_transfer(self, question_type, entities):#question_type是'disease_do_food'等问题类型,entities是['百日咳',...]等实体 if not entities: return [] # 查询语句 sql = [] # 查询疾病的原因 if question_type == 'disease_cause': sql = ["MATCH (m:Disease) where m.name = '{0}' return m.name, m.cause".format(i) for i in entities] # 查询节点m,类型为Disease,当m的属性name为entities,返回m的那么,cause # 查询疾病的防御措施 elif question_type == 'disease_prevent': sql = ["MATCH (m:Disease) where m.name = '{0}' return m.name, m.prevent".format(i) for i in entities] # 查询疾病的持续时间 elif question_type == 'disease_lasttime': sql = ["MATCH (m:Disease) where m.name = '{0}' return m.name, m.cure_lasttime".format(i) for i in entities] # 查询疾病的治愈概率 elif question_type == 'disease_cureprob': sql = ["MATCH (m:Disease) where m.name = '{0}' return m.name, m.cured_prob".format(i) for i in entities] # 查询疾病的治疗方式 elif question_type == 'disease_cureway': sql = ["MATCH (m:Disease) where m.name = '{0}' return m.name, m.cure_way".format(i) for i in entities] # 查询疾病的易发人群 elif question_type == 'disease_easyget': sql = ["MATCH (m:Disease) where m.name = '{0}' return m.name, m.easy_get".format(i) for i in entities] # 查询疾病的相关介绍 elif question_type == 'disease_desc': sql = ["MATCH (m:Disease) where m.name = '{0}' return m.name, m.desc".format(i) for i in entities] # 查询疾病有哪些症状 elif question_type == 'disease_symptom': sql = ["MATCH (m:Disease)-[r:has_symptom]->(n:Symptom) where m.name = '{0}' return m.name, r.name, n.name".format(i) for i in entities] # 查询症状会导致哪些疾病 elif question_type == 'symptom_disease': sql = ["MATCH (m:Disease)-[r:has_symptom]->(n:Symptom) where n.name = '{0}' return m.name, r.name, n.name".format(i) for i in entities] # 查询疾病的并发症 elif question_type == 'disease_acompany': sql1 = ["MATCH (m:Disease)-[r:acompany_with]->(n:Disease) where m.name = '{0}' return m.name, r.name, n.name".format(i) for i in entities] sql2 = ["MATCH (m:Disease)-[r:acompany_with]->(n:Disease) where n.name = '{0}' return m.name, r.name, n.name".format(i) for i in entities] sql = sql1 + sql2 # 查询疾病的忌口 elif question_type == 'disease_not_food': sql = ["MATCH (m:Disease)-[r:no_eat]->(n:Food) where m.name = '{0}' return m.name, r.name, n.name".format(i) for i in entities] # 查询疾病建议吃的东西 elif question_type == 'disease_do_food': sql1 = ["MATCH (m:Disease)-[r:do_eat]->(n:Food) where m.name = '{0}' return m.name, r.name, n.name".format(i) for i in entities] sql2 = ["MATCH (m:Disease)-[r:recommand_eat]->(n:Food) where m.name = '{0}' return m.name, r.name, n.name".format(i) for i in entities] sql = sql1 + sql2 # 已知忌口查疾病 elif question_type == 'food_not_disease': sql = ["MATCH (m:Disease)-[r:no_eat]->(n:Food) where n.name = '{0}' return m.name, r.name, n.name".format(i) for i in entities] # 已知推荐查疾病 elif question_type == 'food_do_disease': sql1 = ["MATCH (m:Disease)-[r:do_eat]->(n:Food) where n.name = '{0}' return m.name, r.name, n.name".format(i) for i in entities] sql2 = ["MATCH (m:Disease)-[r:recommand_eat]->(n:Food) where n.name = '{0}' return m.name, r.name, n.name".format(i) for i in entities] sql = sql1 + sql2 # 查询疾病常用药品-药品别名记得扩充 elif question_type == 'disease_drug': sql1 = ["MATCH (m:Disease)-[r:common_drug]->(n:Drug) where m.name = '{0}' return m.name, r.name, n.name".format(i) for i in entities] sql2 = ["MATCH (m:Disease)-[r:recommand_drug]->(n:Drug) where m.name = '{0}' return m.name, r.name, n.name".format(i) for i in entities] sql = sql1 + sql2 # 已知药品查询能够治疗的疾病 elif question_type == 'drug_disease': sql1 = ["MATCH (m:Disease)-[r:common_drug]->(n:Drug) where n.name = '{0}' return m.name, r.name, n.name".format(i) for i in entities] sql2 = ["MATCH (m:Disease)-[r:recommand_drug]->(n:Drug) where n.name = '{0}' return m.name, r.name, n.name".format(i) for i in entities] sql = sql1 + sql2 # 查询疾病应该进行的检查 elif question_type == 'disease_check': sql = ["MATCH (m:Disease)-[r:need_check]->(n:Check) where m.name = '{0}' return m.name, r.name, n.name".format(i) for i in entities] # 已知检查查询疾病 elif question_type == 'check_disease': sql = ["MATCH (m:Disease)-[r:need_check]->(n:Check) where n.name = '{0}' return m.name, r.name, n.name".format(i) for i in entities] return sql if __name__ == '__main__': handler = QuestionPaser()
3.answer_search.py
from py2neo import Graph#python操作图数据库 class AnswerSearcher: def __init__(self): self.g = Graph('http://localhost:7474', auth=('neo4j', '072766')) self.num_limit = 20#答案的实体数量上限。比如一个疾病可以吃什么食物,最多回答20个 #执行cypher查询,并返回相应结果''' def search_main(self, sqls): final_answers = [] for sql_ in sqls: question_type = sql_['question_type'] queries = sql_['sql'] answers = [] for query in queries: ress = self.g.run(query).data()#返回查询结果 answers += ress final_answer = self.answer_prettify(question_type, answers)#再根据[‘question_type’]的不同调用answer_prettify函数将查询结果和答案话术结合起来。 if final_answer: final_answers.append(final_answer) return final_answers #根据对应的qustion_type,调用相应的回复模板 def answer_prettify(self, question_type, answers): final_answer = [] if not answers: return '' if question_type == 'disease_symptom': desc = [i['n.name'] for i in answers] subject = answers[0]['m.name'] final_answer = '{0}的症状包括:{1}'.format(subject, ';'.join(list(set(desc))[:self.num_limit])) elif question_type == 'symptom_disease': desc = [i['m.name'] for i in answers] subject = answers[0]['n.name'] final_answer = '症状{0}可能染上的疾病有:{1}'.format(subject, ';'.join(list(set(desc))[:self.num_limit])) elif question_type == 'disease_cause': desc = [i['m.cause'] for i in answers] subject = answers[0]['m.name'] final_answer = '{0}可能的成因有:{1}'.format(subject, ';'.join(list(set(desc))[:self.num_limit])) elif question_type == 'disease_prevent': desc = [i['m.prevent'] for i in answers] subject = answers[0]['m.name'] final_answer = '{0}的预防措施包括:{1}'.format(subject, ';'.join(list(set(desc))[:self.num_limit])) elif question_type == 'disease_lasttime': desc = [i['m.cure_lasttime'] for i in answers] subject = answers[0]['m.name'] final_answer = '{0}治疗可能持续的周期为:{1}'.format(subject, ';'.join(list(set(desc))[:self.num_limit])) elif question_type == 'disease_cureway': desc = [';'.join(i['m.cure_way']) for i in answers] subject = answers[0]['m.name'] final_answer = '{0}可以尝试如下治疗:{1}'.format(subject, ';'.join(list(set(desc))[:self.num_limit])) elif question_type == 'disease_cureprob': desc = [i['m.cured_prob'] for i in answers] subject = answers[0]['m.name'] final_answer = '{0}治愈的概率为(仅供参考):{1}'.format(subject, ';'.join(list(set(desc))[:self.num_limit])) elif question_type == 'disease_easyget': desc = [i['m.easy_get'] for i in answers] subject = answers[0]['m.name'] final_answer = '{0}的易感人群包括:{1}'.format(subject, ';'.join(list(set(desc))[:self.num_limit])) elif question_type == 'disease_desc': desc = [i['m.desc'] for i in answers] subject = answers[0]['m.name'] final_answer = '{0},熟悉一下:{1}'.format(subject, ';'.join(list(set(desc))[:self.num_limit])) elif question_type == 'disease_acompany': desc1 = [i['n.name'] for i in answers] desc2 = [i['m.name'] for i in answers] subject = answers[0]['m.name'] desc = [i for i in desc1 + desc2 if i != subject] final_answer = '{0}的症状包括:{1}'.format(subject, ';'.join(list(set(desc))[:self.num_limit])) elif question_type == 'disease_not_food': desc = [i['n.name'] for i in answers] subject = answers[0]['m.name'] final_answer = '{0}忌食的食物包括有:{1}'.format(subject, ';'.join(list(set(desc))[:self.num_limit])) elif question_type == 'disease_do_food': do_desc = [i['n.name'] for i in answers if i['r.name'] == '宜吃'] recommand_desc = [i['n.name'] for i in answers if i['r.name'] == '推荐食谱'] subject = answers[0]['m.name'] final_answer = '{0}宜食的食物包括有:{1}\n推荐食谱包括有:{2}'.format(subject, ';'.join(list(set(do_desc))[:self.num_limit]), ';'.join(list(set(recommand_desc))[:self.num_limit])) elif question_type == 'food_not_disease': desc = [i['m.name'] for i in answers] subject = answers[0]['n.name'] final_answer = '患有{0}的人最好不要吃{1}'.format(';'.join(list(set(desc))[:self.num_limit]), subject) elif question_type == 'food_do_disease': desc = [i['m.name'] for i in answers] subject = answers[0]['n.name'] final_answer = '患有{0}的人建议多试试{1}'.format(';'.join(list(set(desc))[:self.num_limit]), subject) elif question_type == 'disease_drug': desc = [i['n.name'] for i in answers] subject = answers[0]['m.name'] final_answer = '{0}通常的使用的药品包括:{1}'.format(subject, ';'.join(list(set(desc))[:self.num_limit])) elif question_type == 'drug_disease': desc = [i['m.name'] for i in answers] subject = answers[0]['n.name'] final_answer = '{0}主治的疾病有{1},可以试试'.format(subject, ';'.join(list(set(desc))[:self.num_limit])) elif question_type == 'disease_check': desc = [i['n.name'] for i in answers] subject = answers[0]['m.name'] final_answer = '{0}通常可以通过以下方式检查出来:{1}'.format(subject, ';'.join(list(set(desc))[:self.num_limit])) elif question_type == 'check_disease': desc = [i['m.name'] for i in answers] subject = answers[0]['n.name'] final_answer = '通常可以通过{0}检查出来的疾病有{1}'.format(subject, ';'.join(list(set(desc))[:self.num_limit])) return final_answer if __name__ == '__main__': searcher = AnswerSearcher()
4.chatbot_graph.py
from question_classifier import * from question_parser import * from answer_search import * #问答类 class ChatBotGraph: def __init__(self): self.classifier = QuestionClassifier() self.parser = QuestionPaser() self.searcher = AnswerSearcher() def chat_main(self, sent): answer = '您好,我是小鱼医药智能助理,希望可以帮到您。祝您身体棒棒!' res_classify = self.classifier.classify(sent) if not res_classify: return answer#如果没有找到关键词,则返回固定答案 res_sql = self.parser.parser_main(res_classify)#查询语句 final_answers = self.searcher.search_main(res_sql)#根据查询语句返回答案 if not final_answers: return answer else: return '\n'.join(final_answers) if __name__ == '__main__': handler = ChatBotGraph() while 1: question = input('用户:') answer = handler.chat_main(question) print('小鱼:', answer)
实现结果:
(60条消息) 知识图谱的节点和关系实现(python)_python 知识图谱_chen_nnn的博客-CSDN博客
(60条消息) 菜哥学知识图谱(通过“基于医疗知识图谱的问答系统”)(四)(代码分析2)_weixin_40539807的博客-CSDN博客
(60条消息) 基于医疗知识图谱的问答系统源码详解_vivian_ll的博客-CSDN博客
本项目还有不足:关于疾病的起因、预防等,实际返回的是一大段文字,这里其实可以引入事件抽取的概念,进一步将原因结构化表示出来。这个可以后面进行尝试。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。