用python,生活仍有诗和远方

常听说,现在的代码,就和唐朝的诗一样重要。 可对我们来说,写几行代码没什么,但是,要让我们真正地去写一首唐诗,那可就头大了。。既然如此,为何不干脆用代码写一首唐诗?

准备:

  • python3.6环境
  • 推荐使用anaconda管理python包,可以对于每个项目,创建环境,并在该环境下下载项目需要的包。
  • 推荐使用pycharm作为编译器。

GitHub代码:GitHub – theodore3131/TangshiGenerator

具体步骤:

  • 使用爬虫爬取全唐诗,总共抓取了71000首。
#使用urllib3的内置函数构建爬虫的安全验证,来应对网站的反爬虫机制  http = urllib3.PoolManager(       cert_reqs='CERT_REQUIRED',       ca_certs=certifi.where())  #爬虫的目标网站  r = http.request('GET', url)  #爬虫获取的html数据  soup = BeautifulSoup(r.data, 'html.parser')  content = soup.find('div', class_="contson")
  • 使用正则表达式对爬取的数据进行处理
p1 = r"[u4e00-u9fa5]{5,7}[u3002|uff0c]"  #[汉字]{重复5-7次}[中文句号|中文逗号]  pattern1 = re.compile(p1)        #编译正则表达式  result = pattern1.findall(poemfile)   #搜索匹配的字符串,得到匹配列表
  • 对诗词正文进行分词操作
#使用jieba中文分词库的textRank算法来找出各个词性的高频词  for x in jieba.analyse.textrank(content, topK=600, allowPOS=('n', 'nr', 'ns', 'nt', 'nz', 'm')):
  • 唐诗生成
    • 处理韵脚
使用pinyin库
pip install pinyin
verse = pinyin.get("天", format="strip")  #输出:tian

对于韵脚,本来是想找出所有的韵脚并做成字典形式存储起来,但韵脚总共有20多个, 后来发现其实20多个韵脚都是以元音字母开始的,我们可以基于这个规则来判断:

rhythm = ""  rhythmList = ["a", "e", "i", "o", "u"]  verse = pinyin.get(nounlist[i1][1], format="strip")  #韵脚在每个pinyin倒叙最后一个元音字母处截止            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")  #韵脚在每个pinyin倒叙最后一个元音字母处截止            for p in range(len(verse)-1, -1, -1):                if verse[p] in rhythmList:                    ind = p          rhythm = verse[ind:len(verse)]  #确保2,4句的韵脚相同,保证押韵        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/11…

当然,现在生成的唐诗还是比较低级的,属于基础的古诗文词语排列组合。 接下来考虑优化模版,提取五言和七言常用句式作为模版。 另外考虑使用机器学习的方法,写RNN来让计算机自动生成充满韵味的诗