-
Notifications
You must be signed in to change notification settings - Fork 29
/
chat.py
75 lines (61 loc) · 2.16 KB
/
chat.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import json
import os
import random
import logging
import match
from responsesEvaluate import Evaluator
def main():
chatter = GossipBot()
#chatter.randomTalks(num=1000)
chatter.chatTime()
class GossipBot(object):
"""
八卦板聊天機器人 ob'_'ov
"""
def __init__(self,match_type="bm25"):
self.matcher = match.getMatcher(match_type)
self.evaluator = Evaluator()
self.testSegment()
self.defaultResponse = [
"你在說什麼呢?",
"我不太明白你的意思"
]
def testSegment(self):
logging.info("測試斷詞模塊中")
try:
self.matcher.wordSegmentation("測試一下斷詞")
logging.info("測試成功")
except Exception as e:
logging.info(repr(e))
logging.info("模塊載入失敗,請確認data與字典齊全")
def chatTime(self):
print("MianBot: 您好,我是你的老朋友眠寶,讓我們來聊聊八卦吧 o_o ")
while True:
query = input("User: ")
print("MianBot: " +self.getResponse(query))
def getResponse(self,query,threshold=50):
title,index = self.matcher.match(query)
sim = self.matcher.getSimilarity()
if sim < threshold:
random.choice(self.defaultResponse)
else:
res = json.load(open(os.path.join("data/processed/reply/",str(int(index/1000))+'.json'),'r',encoding='utf-8'))
targetId = index % 1000
candiates = self.evaluator.getBestResponse(res[targetId],topk=3)
reply = self.randomPick(candiates)
return reply
def randomPick(self, answers):
try:
answer = random.choice(answers)[0]
except:
answer = "沒有資料"
return answer
def randomTalks(self, num=100):
with open("data/Titles.txt",'r',encoding='utf-8') as data:
titles = [line.strip('\n') for line in data]
for _ in range(num):
query = random.choice(titles)
print("User: " + query)
print("MianBot: " +self.getResponse(query) + "\n")
if __name__=="__main__":
main()