用户:坦率的刺牙螺500查看:0 回复:2 评论:0 创建时间:2020-03-30T12:00:15
【作品展示】

【作品介绍】
你只需要输入王维/李白/陆游/苏轼の诗句,程序就可以猜出作者呦!~~按下运行即可~~
【作品源代码】
import jieba
from nltk.classify import NaiveBayesClassifier
from pyecharts import Pie
import webbrowser
import os
# 收集数据
# 读取苏轼的诗词
with open('sushi.txt', "r", encoding="utf-8-sig") as txt:
text1 = txt.read()
list1 = jieba.lcut(text1)
result1 = " ".join(list1)
# 读取陆游的诗词
with open('luyou.txt', "r", encoding="utf-8-sig") as txt:
text2 = txt.read()
list2 = jieba.lcut(text2)
result2 = " ".join(list2)
# 读取李白的诗词
with open('libai.txt', "r", encoding="utf-8-sig") as txt:
text3 = txt.read()
list3 = jieba.lcut(text3)
result3 = " ".join(list3)
# 读取王维的诗词
with open('wangwei.txt', "r", encoding="utf-8-sig") as txt:
text4 = txt.read()
list4 = jieba.lcut(text4)
result4 = " ".join(list4)
def word_feats(words):
return dict([(word, True) for word in words])
# 苏轼
ss_features = [(word_feats(ss), "ss") for ss in result1]
# 陆游
ly_features = [(word_feats(ly), "ly") for ly in result2]
# 李白
lb_features = [(word_feats(lb), "lb") for lb in result3]
# 王维
ww_features = [(word_feats(ww), "ww") for ww in result4]
train_set = ss_features + ly_features + lb_features + ww_features
classifier = NaiveBayesClassifier.train(train_set)
num = 0
while num < 1:
print("少年,诗落谁家,敢来挑战吗!")
print("我们的游戏规则是:你只需要输入王维/李白/陆游/苏轼の诗句,程序就可以猜出作者呦!~~")
print("------------------------------------------------------------------------")
# 输入诗句
sentence = input("请在这里,输入想到的一句王维/李白/陆游/苏轼的诗词:")
# 诗句分词
words = jieba.lcut(sentence)
print(words)
# 分类统计
# 存放标签次数
ss = 0
ly = 0
lb = 0
ww = 0
# 运用 for 循环遍历 words
for word in words:
print(word)
classResult = classifier.classify(word_feats(word))
if classResult == "ss":
ss += 1
if classResult == "ly":
ly += 1
if classResult == "lb":
lb += 1
if classResult == "ww":
ww += 1
# 统计可能性
su = ss / len(words)
lu = ly / len(words)
li = lb / len(words)
wa = ww / len(words)
# 打印可能性
print("苏轼的可能性:", su)
print("陆游的可能性:", lu)
print("李白的可能性:", li)
print("王维的可能性:", wa)
# 打印诗人
if su > lu and su > li and su > wa:
print("诗人应该是苏轼")
elif lu > su and lu > li and lu > wa:
print("诗人应该是陆游")
elif li > su and li > lu and li > wa:
print("诗人应该是李白")
elif wa > su and wa > lu and wa > li:
print("诗人应该是王维")
else:
print("不是王维/李白/陆游/苏轼的诗,或者可能性相等,或者无法判断,sorry~~")
# 定义标签列表
# 数据列表
attr = ["苏轼", "陆游", "李白", "王维"]
v1 = []
v1.append(su)
v1.append(lu)
v1.append(li)
v1.append(wa)
pie = Pie("少年,诗落谁家,敢来挑战吗?")
pie.add(
"",
attr, v1, # 添加标签列表,数据列表
is_label_show=True, # 显示图表信息
radius=[34, 55], # 圆环内圈,外圈半径
is_random=True, # 图表颜色随机
)
pie.render()
webbrowser.open("file://" + os.path.realpath("render.html"))
print("敢再来一次吗?")
num = int(input("继续敲0,暂停敲1:"))
if num != 0 and num != 1:
print("请按下右上方运行按钮重新运行")
【提示】
部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端:
https://python.codemao.cn