暂无分类
暂无标签
发布于2020-05-17 17:35 阅读(448) 评论(0) 点赞(10) 收藏(2)
0
1
2
3
4
5
6
7
8
9
Python实现的“为你写诗”,可用于体验学习!
1、将诗句保存到同一个目录下的“poem.txt”文件,注意编码是UTF-8
2、运行以下程序:先是读入诗句,生成“poem.vex”,然后你就可以输入关键词得到相关诗句了!
1、诗句越多,越能作诗;诗句太少,无法作诗!
2、修改“poem.txt”后,建议删除“poem.vec”后再重新运行程序。
from gensim.models import Word2Vec # 词向量
from random import choice
from os.path import exists
import warnings
warnings.filterwarnings('ignore') # 不打印警告
class CONF:
path = 'poem.txt'
window = 16 # 滑窗大小
min_count = 60 # 过滤低频字
size = 125 # 词向量维度
topn = 14 # 生成诗词的开放度
model_path = 'poem.vec'
class Model:
def __init__(self, window, topn, model):
self.window = window
self.topn = topn
self.model = model # 词向量模型
self.chr_dict = model.wv.index2word # 字典
"""模型初始化"""
@classmethod
def initialize(cls, config):
if exists(config.model_path):
# 模型读取
model = Word2Vec.load(config.model_path)
else:
# 语料读取
with open(config.path, encoding='utf-8') as f:
ls_of_ls_of_c = [list(line.strip()) for line in f]
# 模型训练和保存
model = Word2Vec(ls_of_ls_of_c, size=config.size,
window=config.window, min_count=config.min_count)
model.save(config.model_path)
return cls(config.window, config.topn, model)
"""古诗词生成"""
def poem_generator(self, title, form):
filter = lambda lst: [t[0] for t in lst if t[0] not in [',', '。']]
# 标题补全
if len(title) < 4:
if not title:
title += choice(self.chr_dict)
for _ in range(4 - len(title)):
similar_chr = self.model.similar_by_word(title[-1], self.topn // 2)
similar_chr = filter(similar_chr)
char = choice([c for c in similar_chr if c not in title])
title += char
# 文本生成
poem = list(title)
for i in range(form[0]):
for _ in range(form[1]):
predict_chr = self.model.predict_output_word(
poem[-self.window:], max(self.topn, len(poem) + 1))
predict_chr = filter(predict_chr)
char = choice([c for c in predict_chr if c not in poem[len(title):]])
poem.append(char)
poem.append(',' if i % 2 == 0 else '。')
length = form[0] * (form[1] + 1)
return '《%s》' % ''.join(poem[:-length]) + '\n' + ''.join(poem[-length:])
def main(config=CONF):
form = {'五言绝句': (4, 5), '七言绝句': (4, 7), '对联': (2, 9)}
m = Model.initialize(config)
while True:
title = input('输入标题:').strip()
if title == '':
break
try:
poem = m.poem_generator(title, form['五言绝句'])
print('\033[031m五言绝句:%s\033[0m' % poem) # red
poem = m.poem_generator(title, form['七言绝句'])
print('\033[033m七言绝句:%s\033[0m' % poem) # yellow
poem = m.poem_generator(title, form['对联'])
print('\033[036m对联:%s\033[0m' % poem) # purple
print()
except:
print("对不起,我作不出这类诗词!")
pass
if __name__ == '__main__':
main()
相关开源项目:https://gitee.com/arye/dl/tree/master/NLP/gensim%E6%96%87%E6%9C%AC%E7%94%9F%E6%88%90
在线测试平台:https://python.jupyter.vip/
体验程序下载:https://download.csdn.net/download/crxis/12424344
原文链接:https://blog.csdn.net/crxis/article/details/106147665
0
1
2
3
4
5
6
7
8
作者:9384vfnv
链接: https://www.pythonheidong.com/blog/article/377281/eebf75c95cac41e92369/
来源: python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系z452as@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!