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

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