1 Star 1 Fork 0

陈某某/数字语音处理

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
基于txt词典的问答式机器人(UI) 10.48 KB
一键复制 编辑 原始数据 按行查看 历史
import tkinter as tk
from functools import partial
import jieba
import pyttsx3
#将输入的字符串分解成一个列表并返回 逆序排列并返回
def ai_StrSplit(String):
'''
Decompose the string into a list #将字符串分解为一个列表
:param String: The string to be decompased #要分解的字符串
:return: String_lt #分解后的字符串列表
'''
String_lt=jieba.lcut(String,cut_all=True) # 要引入jieba库
String1=jieba.lcut(String,cut_all=True)
String2=jieba.lcut(String,cut_all=True)
String3=jieba.lcut(String,cut_all=True)
String3.append('') # 给string3添加一个空字符串
for Str1 in String1:
String2.remove(Str1) # 从string2中移除当前字符(Str1)
for Str2 in String2:
try:
String3.remove(Str1) # 尝试从string3中移除Str1
except:
pass
try:
String3.remove(Str2) # 尝试从string3中移除Str2
except:
pass
for Str3 in String3:
String_lt.append(Str1+Str2+Str3) # 将分解出的单词(Str1、Str2和Str3)合并并添加到String_lt列表中
String_lt=sorted(String_lt,reverse=True) # 将String_lt按照字典序逆序排列
return String_lt # 返回分解后的字符串列表
#将输入的字符串与字典文件进行匹配 并返回匹配结果和判断匹配是否成功的标志
def ai_MatchSiple(path,String):
'''
Matches the dictionary to a single string
:param path: The dicttionary to match #匹配的字典
:param String: The string to match #要匹配的字符串
:return: lt_ms #匹配结果与判断(1有/0无)的列表
'''
'''
f1=f.readlines().split('\n')[0]
f2=f.readlines().split('\n')[0]
f3=f.readlines()
'''
errow_matchsplit=0 # 匹配和切分过程是否出错的标志,初始化为0
back=None # 如果匹配成功,则将对应的值存储到此变量中;否则此变量维持None状态
# 打开文件,进行读取操作
with open(path,'r',encoding='utf-8') as f:
while errow_matchsplit==0: # 只要还没有匹配成功且没有出现异常,就继续循环
f1 = f.readline().strip() # 读取一行并去除首尾空格,存储到f1中
f2 = f.readline().strip() # 读取下一行并进行相同处理,存储到f2中
f3 = f.readline().strip() # 读取再下一行并进行相同处理,存储到f3中
if String==f1: # 如果String等于f1所存储的字符串,则表示匹配成功
back=f2 # 将对应的值存储到back中
errow_matchsplit=1 # 将标志位置为1,表示匹配过程成功完成
break # 跳出循环
if f1=='' or f2=='': # 如果读取了空行,则跳出循环
break
lt_ms=[back,errow_matchsplit] # 将结果存储到列表中
return lt_ms # 返回结果列表
#匹配一个字典(通过传入的文件路径)和一个字符串列表
def ai_MatchHeight(path,String_lt):
'''
Matches the dictionary to a single string #用字符串列表匹配字典
:param path: The dicttionary to match #匹配的字典
:param String_lt: list of strings to match #要匹配的字符串列表
:return: lt_mh #匹配结果与判断(1有/2无)的列表
'''
errow_matchheight=0 # 初始化标志位为0,表示还未匹配到
back=None # 匹配结果初始化为空
with open(path,'r',encoding='utf-8') as f: # 打开文件/注意编码
while errow_matchheight==0: # 标志位为0时进入循环
f1 = f.readline().strip() # 读取一行内容并去掉空格和换行符
f2 = f.readline().strip()
f3 = f.readline().strip()
for String in String_lt: # 遍历待匹配的字符串列表
if String==f1: # 如果当前字符串能够与字典中的某个值匹配成功
back=f2 # 则将该键对应的值记录在back变量中
errow_matchheight=1 # 并将标志位置为1,表示已经匹配成功
break # 跳出for循环
if f1 == '' or f2=='': # 如果仍然有数据行,则继续匹配;否则跳出循环
break
lt_mh=[back,errow_matchheight] # 将匹配结果和标志位组成一个列表
return lt_mh # 返回结果
#向一个字典文件中写入匹配语句和匹配结果
def ai_study(path,study_start,study_end):
'''
Open the dictionary and write the match statement and the match result #打开字典并编写匹配的语句和匹配的结果
:param path: The dictionary to open #要查的字典
:param study_start: Dictionary matching statements #字典匹配语句
:param study_end: The dictionary returns the result #字典返回结果
:return: None #无返回
'''
with open(path,'a',encoding='utf-8') as f: # 使用with语句打开文件,并以utf-8编码方式附加写入
f.write(study_start+'\n') # 将匹配语句写入文件
f.write(study_end+'\n') # 将匹配结果写入文件
f.write('\n') # 写入一个空行,方便下一次写入
#聊天机器人的交互逻辑
def ai_study_gui():
path = "data/cy的AI聊天库.txt"
def study():
study_start = entry_question.get()
study_end = entry_answer.get()
if study_start and study_end:
ai_study(path=path, study_start=study_start, study_end=study_end)
label_status.config(text="学习完成!")
entry_question.delete(0, tk.END)
entry_answer.delete(0, tk.END)
#根据输入的问题进行匹配并输出回答 如果匹配不成功,则会给出学习的提示 当用户输入"exit"时,程序退出
def chat(event=None):
String = entry_input.get()
if String != "exit":
a1 = ai_MatchSiple(path=path, String=String) # 匹配简单模式
show = a1[0] # 匹配结果
errow_matchsimple = a1[1] # 是否匹配成功
engine = pyttsx3.init() # 初始化语音合成引擎
engine.setProperty('rate', 150) # 设置语速为 150
engine.setProperty('volume', 1) # 设置音量为 1
if errow_matchsimple == 0: # 如果匹配不成功
String_lt = ai_StrSplit(String=String) # 分词
a2 = ai_MatchHeight(path=path, String_lt=String_lt) # 匹配高级模式
show = a2[0] # 匹配结果
errow_matchight = a2[1] # 是否匹配成功
if errow_matchight == 0: # 如果匹配不成功 # and (errow_study=='y' or errow_study=='yes')
label_status.config(text="小四: 您可以输入问题进行学习哦!")
else:
label_output.config(text="小四:" + show)
engine.say(show) # 添加语音播报功能
engine.runAndWait()
else:
label_output.config(text="小四:" + show)
engine.say(show) # 添加语音播报功能
engine.runAndWait()
else:
root.quit()
# 创建一个根窗口
root = tk.Tk()
root.title("CY的聊天机器人") # 设置窗口标题
root.geometry("400x300") # 设置窗口大小
# 问题输入框
frame_question = tk.Frame(root)
frame_question.pack(pady=10)
#创建一个标签用于显示“请输入问题:”
label_question = tk.Label(frame_question, text="请输入问题:")
label_question.pack(side=tk.LEFT)
#创建一个文本框,用于输入问题
entry_question = tk.Entry(frame_question, width=30)
entry_question.pack(side=tk.LEFT)
# 回答输入框
frame_answer = tk.Frame(root)
frame_answer.pack(pady=10)
#创建一个标签用于显示“请输入回答:”
label_answer = tk.Label(frame_answer, text="请输入回答:")
label_answer.pack(side=tk.LEFT)
#创建一个文本框,用于输入问题
entry_answer = tk.Entry(frame_answer, width=30)
entry_answer.pack(side=tk.LEFT)
# 创建一个学习按钮,并指定点击时调用函数为ai_study
button_study = tk.Button(root, text="学习", command=study)
button_study.pack(pady=10)
# 输入输出框
frame_chat = tk.Frame(root)
frame_chat.pack(pady=10)
#创建一个标签用于显示“我:”
label_input = tk.Label(frame_chat, text="我:")
label_input.grid(row=0, column=0)
#创建一个文本框,用于输入对话内容
entry_input = tk.Entry(frame_chat, width=30)
entry_input.grid(row=0, column=1)
#创建一个发按钮,并指定点击时调用的函数为chat
button_send = tk.Button(frame_chat, text="发送", command=chat)
button_send.grid(row=0, column=2)
# 创建一个标签用于显示机器人回答的内容
label_output = tk.Label(frame_chat, text="")
label_output.grid(row=1, columnspan=3)
# 创建一个状态栏,显示当前机器人的状态信息
label_status = tk.Label(root, text="小四: 您可以向我提问")
label_status.pack(side=tk.BOTTOM)
entry_input.bind('<Return>',chat) # 监听按键事件(用回车键作为发送)
root.mainloop() #进入消息循环
#如果这个脚本是主程序,则执行ai_study_gui()函数来启动程序
if __name__ == '__main__':
ai_study_gui()
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/goodchenY/digital-voice-processing.git
git@gitee.com:goodchenY/digital-voice-processing.git
goodchenY
digital-voice-processing
数字语音处理
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891