前言
课程设计自己选了这个课题,因为之前就对NLP(Natural Language Processing)有一些兴趣,英语文献综述也是以这个为主题来写的。虽然只学了一点点皮毛,哈哈其实还是挺有趣的
准备
本项目用到的开发环境
使用软件
PyCharm,写pythonNavicat premium 15,数据库图形化工具Visual Studio Code,嘿嘿
GUI开发
python的GUI开发,最简洁的当然是Tkinter了,但是我觉得应该牛批高级一些,就选用了PyQt5库来开发机器人的图形化界面。
首先,感谢大佬的文章python GUI库图形界面开发之PyQt5美化窗体与控件(异形窗体)实例
我的程序也是基于这个框架来改的
看看效果先
聊天模块1.0版本
聊天模块想到最简单的方法就是调用API接口了,
- 首先可以去图灵机器人注册一个账号
- 登录后点击 创建机器人
- 在机器人设置界面找到你的 apikey
创建req.json文件
{
"perception":
{
"inputText":
{
"text": ""
},
"selfInfo":
{
"location":
{
"city": "北京",
"province": "北京",
"street": "天安门"
}
}
},
"userInfo":
{
"apiKey": "你的",
"userId": "你的"
}
}
建立python文件
#coding=utf-8
import json
import urllib.request
api_url = "http://openapi.tuling123.com/openapi/api/v2"
json_path = \'req.json\'
class TuringDome(object):
def __init__(self,json_path="",api_url=""):
self.json_path = json_path
self.api_url = api_url
self.text_input = input(\'请输入我的问话\n我:\')
def readJson(self):
\'\'\'获取json文件\'\'\'
with open(self.json_path,\'r\',encoding=\'utf-8\') as f_json:
json_data = json.load(f_json)
return json_data
def textInput(self):
\'\'\'用变量text_input替换text的value值\'\'\'
req = self.readJson()
req[\'perception\'][\'inputText\'][\'text\'] = self.text_input
return req
def dumpsJson(self):
\'\'\'将json字符串转化成dict格式\'\'\'
req = self.textInput()
req = json.dumps(req,sort_keys=True,indent=4,).encode(\'utf8\')
return req
def urllibRequestResponse(self):
req = self.dumpsJson()
http_post = urllib.request.Request(self.api_url, data=req, headers={\'content-type\': \'application/json\'})
response = urllib.request.urlopen(http_post)# 在urlopen()方法中传入字符串格式的url地址,则此方法会访问目标网址,然后返回访问的结果。
response_str = response.read().decode(\'utf8\')
response_dict = json.loads(response_str) # 将字符串response_str转成字典
return response_dict
def getTuringResponse(self):
\'\'\'取得机器人返回的语句并输出\'\'\'
response_dict = self.urllibRequestResponse()
intent_code = response_dict.get(\'intent\')[\'code\']
results_text = response_dict.get(\'results\')[0][\'values\'][\'text\']
print(\'Turing的回答:\')
print(\'code:\' + str(intent_code))
print(\'text:\' + results_text)
def talkToTheTuring(self):
#self.text_input = input(\'请输入我的问话\n我:\')
while True:
if self.text_input != "exit:":
self.getTuringResponse()
self.text_input = input(\'请输入我的问话\n我:\')
else:
print("*****结束对话!*****")
break
if __name__ == \'__main__\':
#pass
td = TuringDome(json_path=json_path,api_url=api_url)
td.talkToTheTuring()
差不多就可以合并到GUI里面了
效果还不错
语音合成1.0版本
语音合成模块如果不调用API,同时又不想自己训练的话,可以有两个选择
-
win32com.clientimport win32com.client speaker = win32com.client.Dispatch("SAPI.SpVoice") speaker.Speak("Hello, it works!") -
pyttsx# coding:utf-8 import sys reload(sys) sys.setdefaultencoding(\'utf8\') import pyttsx engine = pyttsx.init() engine.say(\'hello world\') engine.runAndWait() # 朗读一次 engine.endLoop()版本1.0
就这样,程序的初级框架功能就基本上有了,但是还是有些地方不尽如人意,比如聊天机器人是调用的接口而不是自己训练的,语音合成功能声音不好听,语音识别的录音功能还没有实装,其他小功能也还为实现。
所以接下来会再写一篇程序优化和完善的聊天机器人版本2.0。
代码还在完善,有需要可以私信哦