为你写诗
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)