常听说,现在的代码,就和唐朝的诗一样重要。
可对我们来说,写几行代码没什么,但是,要让我们真正地去写一首唐诗,那可就头大了。。既然如此,为何不干脆用代码写一首唐诗?
准备:
GitHub代码:
https://github.com/theodore3131/TangshiGenerator
具体步骤:
使用爬虫爬取全唐诗,总共抓取了71000首。
http = urllib3.PoolManager(
cert_reqs='CERT_REQUIRED',
ca_certs=certifi.where())
r = http.request('GET', url)
soup = BeautifulSoup(r.data, 'html.parser')
content = soup.find('div', class_="contson")
使用正则表达式对爬取的数据进行处理
p1 = r"[一-龥]{5,7}[。|,]"
pattern1 = re.compile(p1)
result = pattern1.findall(poemfile)
对诗词正文进行分词操作
for x in jieba.analyse.textrank(content, topK=600, allowPOS=('n', 'nr', 'ns', 'nt', 'nz', 'm')):
唐诗生成,
处理韵脚
pip install pinyin
verse = pinyin.get("天", format="strip")
对于韵脚,本来是想找出所有的韵脚并做成字典形式存储起来,但韵脚总共有20多个,
后来发现其实20多个韵脚都是以元音字母开始的,我们可以基于这个规则来判断:
rhythm = ""
rhythmList = ["a", "e", "i", "o", "u"]
verse = pinyin.get(nounlist[i1][1], format="strip")
for p in range(len(verse)-1, -1, -1):
if verse[p] in rhythmList:
ind = p
rhythm = verse[ind:len(verse)]
目前是最初级的五言律诗,且为名动名句式
rhythm = ""
rhythmList = ["a", "e", "i", "o", "u"]
while num < 4:
i = random.randint(1, len(nounlist)-1)
i1 = random.randint(1, len(nounlist)-1)
j = random.randint(1, len(verblist)-1)
ind = 0
ind1 = 0
if (num == 1):
rhythm = ""
verse = pinyin.get(nounlist[i1][1], format="strip")
for p in range(len(verse)-1, -1, -1):
if verse[p] in rhythmList:
ind = p
rhythm = verse[ind:len(verse)]
if (num == 3):
ind1 = 0
verse1 = pinyin.get(nounlist[i1][1], format="strip")
for p in range(len(verse1)-1, -1, -1):
if verse1[p] in rhythmList:
ind1 = p
while verse1[ind1: len(verse1)] != rhythm:
i1 = random.randint(1, len(nounlist)-1)
verse1 = pinyin.get(nounlist[i1][1], format="strip")
for p in range(len(verse1)-1, -1, -1):
if verse1[p] in rhythmList:
ind1 = p
print(nounlist[i]+verblist[j][1]+nounlist[i1])
num += 1
藏头诗
其实思路很简单,既然我们有了语料库,那么,我们每次在排列组合词的时候,只需保证生成每句时,第一个名词的第一个字,是按序给定四字成语中的即可
for x in range(len(nounlist)):
if nounlist[x][0] == str[num]:
i = x
来看一下结果:
四言诗:
所思浮云
关山车马
高楼流水
闲人肠断
五言律诗:
西风时细雨
山川钓建章
龙门看萧索
几年乡斜阳
藏头诗:
落花流水
落晖首南宫
花枝成公子
流水名朝廷
水声胜白石
参考:
https://segmentfault.com/a/1190000004571958
当然,现在生成的唐诗还是比较低级的,属于基础的古诗文词语排列组合。
接下来考虑优化模版,提取五言和七言常用句式作为模版。
另外考虑使用机器学习的方法,写RNN来让计算机自动生成充满韵味的诗。
来源:TheodoreXu