Python AI智能聊天
- 首先項目需要的包
import urllib.request
import urllib.parse
from tkinter import *
import time
- 函數(shù)部分
說明:調(diào)用服務(wù)器接口,實現(xiàn)非特定智能回復
def get_robot_replay(question):
'''
函數(shù)功能:對于特定的問題進行特定的回答,對于其他非特定的問題進行智能回復
參數(shù)描述:
question:聊天內(nèi)容或者問題
返回值:str,回復內(nèi)容
'''
if "你叫什么名字"in question:
answer ="我是游游"
elif "你多少歲"in question:
answer="18"
elif "你是GG還是MM"in question:
answer="MM"
else:
try:
# 調(diào)用NLP接口實現(xiàn)智能回復
params=urllib.parse.urlencode({'msg':question}).encode() #將str轉(zhuǎn)換成字節(jié)類型,參數(shù)接口需要進行URL編碼
req = urllib.request.Request("http://api.itmojun.com/chat_robot",params,method="POST")#創(chuàng)建請求對象
answer=urllib.request.urlopen(req).read().decode()#調(diào)用接口(向目標服務(wù)器發(fā)送HTTP請求)
except Exception as e:
answer="AI機器人出現(xiàn)故障!(原因:%s)" % e
return answer
- 回復格式方面以及界面設(shè)計
def msgsend():
msg = '我' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + '\n'
txt_msglist.insert(END, msg, 'green') # 添加時間
txt_msglist.insert(END, txt_msgsend.get('0.0', END)) # 獲取發(fā)送消息,添加文本到消息列表
msg1 = '游游大寶貝' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + '\n'
txt_msglist.insert(END, msg1, 'green') # 添加時間
txt_msglist.insert(END,get_robot_replay(txt_msgsend.get('0.0', END)))
txt_msgsend.delete('0.0', END) # 清空發(fā)送消息
def cancel():
txt_msgsend.delete('0.0', END) # 取消發(fā)送消息,即清空發(fā)送消息
'''綁定up鍵'''
def msgsendEvent(event):
if event.keysym == 'Up':
msgsend()
- 聊天界面設(shè)計
tk = Tk()
tk.title('和游游大寶貝的秘聊')
'''創(chuàng)建分區(qū)'''
f_msglist = Frame(height=300, width=300) # 創(chuàng)建<消息列表分區(qū) >
f_msgsend = Frame(height=300, width=300) # 創(chuàng)建<發(fā)送消息分區(qū) >
f_floor = Frame(height=100, width=300) # 創(chuàng)建<按鈕分區(qū)>
f_right = Frame(height=700, width=100) # 創(chuàng)建<圖片分區(qū)>
'''創(chuàng)建控件'''
txt_msglist = Text(f_msglist) # 消息列表分區(qū)中創(chuàng)建文本控件
txt_msglist.tag_config('green', foreground='blue') # 消息列表分區(qū)中創(chuàng)建標簽
txt_msgsend = Text(f_msgsend) # 發(fā)送消息分區(qū)中創(chuàng)建文本控件
txt_msgsend.bind('
', msgsendEvent) # 發(fā)送消息分區(qū)中,綁定‘UP’鍵與消息發(fā)送。
'''txt_right = Text(f_right) #圖片顯示分區(qū)創(chuàng)建文本控件'''
button_send = Button(f_floor, text='Sendz', command=msgsend) # 按鈕分區(qū)中創(chuàng)建按鈕并綁定發(fā)送消息函數(shù)
button_cancel = Button(f_floor, text='Cancel', command=cancel) # 分區(qū)中創(chuàng)建取消按鈕并綁定取消函數(shù)
'''分區(qū)布局'''
f_msglist.grid(row=0, column=0) # 消息列表分區(qū)
f_msgsend.grid(row=1, column=0) # 發(fā)送消息分區(qū)
f_floor.grid(row=2, column=0) # 按鈕分區(qū)
f_right.grid(row=0, column=1, rowspan=3) # 圖片顯示分區(qū)
txt_msglist.grid() # 消息列表文本控件加載
txt_msgsend.grid() # 消息發(fā)送文本控件加載
button_send.grid(row=0, column=0, sticky=W) # 發(fā)送按鈕控件加載
button_cancel.grid(row=0, column=1, sticky=W) # 取消按鈕控件加載
tk.mainloop()
- 運行截圖
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
