以下是经过Python3.6.4调试通过的代码,与大家分享:
1、听两个聊天机器人互相聊天
2、AI分析唐诗的作者是李白还是杜甫
① 没事闲的时候,听两个聊天机器人互相聊天
from time import sleep
import requests
s = input("请主人输入话题:")
while True:
resp = requests.post("http://www.tuling123.com/openapi/api",data={"key":"4fede3c4384846b9a7d0456a5e1e2943", "info": s, })
resp = resp.json()
sleep(1)
print('小鱼:', resp['text'])
s = resp['text']
resp = requests.get("http://api.qingyunke.com/api.php", {'key': 'free', 'appid':0, 'msg': s})
resp.encoding = 'utf8'
resp = resp.json()
sleep(1)
print('菲菲:', resp['content'])
#网上还有一个据说智商比较高的小i机器人,用爬虫的功能来实现一下:
import urllib.request
import re
while True:
x = input("主人:")
x = urllib.parse.quote(x)
link = urllib.request.urlopen(
"http://nlp.xiaoi.com/robot/webrobot?&callback=__webrobot_processMsg&data=%7B%22sessionId%22%3A%22ff725c236e5245a3ac825b2dd88a7501%22%2C%22robotId%22%3A%22webbot%22%2C%22userId%22%3A%227cd29df3450745fbbdcf1a462e6c58e6%22%2C%22body%22%3A%7B%22content%22%3A%22" + x + "%22%7D%2C%22type%22%3A%22txt%22%7D")
html_doc = link.read().decode()
reply_list = re.findall(r'\"content\":\"(.+?)\\r\\n\"', html_doc)
print("小i:" + reply_list[-1])
② 分析唐诗的作者是李白还是杜甫
import jieba
from nltk.classify import NaiveBayesClassifier
# 需要提前把李白的诗收集一下,放在libai.txt文本中。
text1 = open(r"libai.txt", "rb").read()
list1 = jieba.cut(text1)
result1 = " ".join(list1)
# 需要提前把杜甫的诗收集一下,放在dufu.txt文本中。
text2 = open(r"dufu.txt", "rb").read()
list2 = jieba.cut(text2)
result2 = " ".join(list2)
# 数据准备
libai = result1
dufu = result2
# 特征提取
def word_feats(words):
return dict([(word, True) for word in words])
libai_features = [(word_feats(lb), 'lb') for lb in libai]
dufu_features = [(word_feats(df), 'df') for df in dufu]
train_set = libai_features + dufu_features
# 训练决策
classifier = NaiveBayesClassifier.train(train_set)
# 分析测试
sentence = input("请输入一句你喜欢的诗:")
print("\n")
seg_list = jieba.cut(sentence)
result1 = " ".join(seg_list)
words = result1.split(" ")
# 统计结果
lb = 0
df = 0
for word in words:
classResult = classifier.classify(word_feats(word))
if classResult == 'lb':
lb = lb + 1
if classResult == 'df':
df = df + 1
# 呈现比例
x = float(str(float(lb) / len(words)))
y = float(str(float(df) / len(words)))
print('李白的可能性:%.2f%%' % (x * 100))
print('杜甫的可能性:%.2f%%' % (y * 100))
————————————————
版权声明:本文为CSDN博主「沅沅说python」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qxr333000/article/details/120221743