介绍
该项目的思路如下:
利用爬虫爬取诗歌,制作诗歌语料库;
将诗歌分句,形成字典:键(key)为该句首字的拼音,值(value)为该拼音对应的诗句,并将字典保存为pickle文件;
读取pickle文件,编写程序,以exe文件形式运行该程序。
该项目实现的诗歌接龙,规则为下一句的首字与上一句的尾字的拼音(包括声调)一致。下面将分步讲述该项目的实现过程。
诗歌语料库
首先,我们利用python爬虫来爬取诗歌,制作语料库。爬取的网址为:https://www.gushiwen.org,页面如下:
由于本文主要为试了展示该项目的思路,因此,只爬取了该页面中的唐诗三百首、古诗三百、宋词三百、宋词精选,一共大约1100多首诗歌。为了加速爬虫,采用并发实现爬虫,并保存到poem.txt文件。完整的python程序如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
import re
import requests
from bs4 import beautifulsoup
from concurrent.futures import threadpoolexecutor, wait, all_completed
# 爬取的诗歌网址
urls = [ 'https://so.gushiwen.org/gushi/tangshi.aspx' ,
'https://so.gushiwen.org/gushi/sanbai.aspx' ,
'https://so.gushiwen.org/gushi/songsan.aspx' ,
'https://so.gushiwen.org/gushi/songci.aspx'
]
poem_links = []
# 诗歌的网址
for url in urls:
# 请求头部
headers = { 'user-agent' : 'mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/67.0.3396.87 safari/537.36' }
req = requests.get(url, headers = headers)
soup = beautifulsoup(req.text, "lxml" )
content = soup.find_all( 'div' , class_ = "sons" )[ 0 ]
links = content.find_all( 'a' )
for link in links:
poem_links.append( 'https://so.gushiwen.org' + link[ 'href' ])
poem_list = []
# 爬取诗歌页面
def get_poem(url):
#url = 'https://so.gushiwen.org/shiwenv_45c396367f59.aspx'
# 请求头部
headers = { 'user-agent' : 'mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/67.0.3396.87 safari/537.36' }
req = requests.get(url, headers = headers)
soup = beautifulsoup(req.text, "lxml" )
poem = soup.find( 'div' , class_ = 'contson' ).text.strip()
poem = poem.replace( ' ' , '')
poem = re.sub(re. compile (r "\([\s\s]*?\)" ), '', poem)
poem = re.sub(re. compile (r "([\s\s]*?)" ), '', poem)
poem = re.sub(re. compile (r "。\([\s\s]*?)" ), '', poem)
poem = poem.replace( '!' , '!' ).replace( '?' , '?' )
poem_list.append(poem)
# 利用并发爬取
executor = threadpoolexecutor(max_workers = 10 ) # 可以自己调整max_workers,即线程的个数
# submit()的参数: 第一个为函数, 之后为该函数的传入参数,允许有多个
future_tasks = [executor.submit(get_poem, url) for url in poem_links]
# 等待所有的线程完成,才进入后续的执行
wait(future_tasks, return_when = all_completed)
# 将爬取的诗句写入txt文件
poems = list ( set (poem_list))
poems = sorted (poems, key = lambda x: len (x))
for poem in poems:
poem = poem.replace( '《' ,' ').replace(' 》 ',' ') \
.replace( ':' , ' ').replace(' “ ', ' ')
print (poem)
with open ( 'f://poem.txt' , 'a' ) as f:
f.write(poem)
f.write( '\n' )
|
该程序爬取了1100多首诗歌,并将诗歌保存至poem.txt文件,形成我们的诗歌语料库。当然,这些诗歌并不能直接使用,需要清理数据,比如有些诗歌标点不规范,有些并不是诗歌,只是诗歌的序等等,这个过程需要人工操作,虽然稍显麻烦,但为了后面的诗歌分句效果,也是值得的。
诗歌分句
有了诗歌语料库,我们需要对诗歌进行分句,分句的标准为:按照结尾为。?!进行分句,这可以用正则表达式实现。之后,将分句好的诗歌写成字典:键(key)为该句首字的拼音,值(value)为该拼音对应的诗句,并将字典保存为pickle文件。完整的python代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
import re
import pickle
from xpinyin import pinyin
from collections import defaultdict
def main():
with open ( 'f://poem.txt' , 'r' ) as f:
poems = f.readlines()
sents = []
for poem in poems:
parts = re.findall(r '[\s\s]*?[。?!]' , poem.strip())
for part in parts:
if len (part) > = 5 :
sents.append(part)
poem_dict = defaultdict( list )
for sent in sents:
print (part)
head = pinyin().get_pinyin(sent, tone_marks = 'marks' , splitter = ' ' ).split()[ 0 ]
poem_dict[head].append(sent)
with open ( './poemdict.pk' , 'wb' ) as f:
pickle.dump(poem_dict, f)
main()
|
我们可以看一下该pickle文件(poemdict.pk)的内容:
当然,一个拼音可以对应多个诗歌。
诗歌接龙
读取pickle文件,编写程序,以exe文件形式运行该程序。
为了能够在编译形成exe文件的时候不出错,我们需要改写xpinyin模块的_init_.py文件,将该文件的全部代码复制至mypinyin.py,并将代码中的下面这句代码
1
2
|
data_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'mandarin.dat' )
|
改写为
1
|
data_path = os.path.join(os.getcwd(), 'mandarin.dat' )
|
这样我们就完成了mypinyin.py文件。
接下来,我们需要编写诗歌接龙的代码(poem_jielong.py),完整代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
import pickle
from mypinyin import pinyin
import random
import ctypes
std_input_handle = - 10
std_output_handle = - 11
std_error_handle = - 12
foreground_darkwhite = 0x07 # 暗白色
foreground_blue = 0x09 # 蓝色
foreground_green = 0x0a # 绿色
foreground_skyblue = 0x0b # 天蓝色
foreground_red = 0x0c # 红色
foreground_pink = 0x0d # 粉红色
foreground_yellow = 0x0e # 黄色
foreground_white = 0x0f # 白色
std_out_handle = ctypes.windll.kernel32.getstdhandle(std_output_handle)
# 设置cmd文字颜色
def set_cmd_text_color(color, handle = std_out_handle):
bool = ctypes.windll.kernel32.setconsoletextattribute(handle, color)
return bool
# 重置文字颜色为暗白色
def resetcolor():
set_cmd_text_color(foreground_darkwhite)
# 在cmd中以指定颜色输出文字
def cprint(mess, color):
color_dict = {
'蓝色' : foreground_blue,
'绿色' : foreground_green,
'天蓝色' : foreground_skyblue,
'红色' : foreground_red,
'粉红色' : foreground_pink,
'黄色' : foreground_yellow,
'白色' : foreground_white
}
set_cmd_text_color(color_dict[color])
print (mess)
resetcolor()
color_list = [ '蓝色' , '绿色' , '天蓝色' , '红色' , '粉红色' , '黄色' , '白色' ]
# 获取字典
with open ( './poemdict.pk' , 'rb' ) as f:
poem_dict = pickle.load(f)
#for key, value in poem_dict.items():
#print(key, value)
mode = str ( input ( 'choose mode(1 for 人工接龙, 2 for 机器接龙): ' ))
while true:
try :
if mode = = '1' :
enter = str ( input ( '\n请输入一句诗或一个字开始:' ))
while enter ! = 'exit' :
test = pinyin().get_pinyin(enter, tone_marks = 'marks' , splitter = ' ' )
tail = test.split()[ - 1 ]
if tail not in poem_dict.keys():
cprint( '无法接这句诗。\n' , '红色' )
mode = 0
break
else :
cprint( '\n机器回复:%s' % random.sample(poem_dict[tail], 1 )[ 0 ], random.sample(color_list, 1 )[ 0 ])
enter = str ( input ( '你的回复:' ))[: - 1 ]
mode = 0
if mode = = '2' :
enter = input ( '\n请输入一句诗或一个字开始:' )
for i in range ( 10 ):
test = pinyin().get_pinyin(enter, tone_marks = 'marks' , splitter = ' ' )
tail = test.split()[ - 1 ]
if tail not in poem_dict.keys():
cprint( '------>无法接下去了啦...' , '红色' )
mode = 0
break
else :
answer = random.sample(poem_dict[tail], 1 )[ 0 ]
cprint( '(%d)--> %s' % (i + 1 , answer), random.sample(color_list, 1 )[ 0 ])
enter = answer[: - 1 ]
print ( '\n(*****最多展示前10回接龙。*****)' )
mode = 0
except exception as err:
print (err)
finally :
if mode not in [ '1' , '2' ]:
mode = str ( input ( '\nchoose mode(1 for 人工接龙, 2 for 机器接龙): ' ))
|
现在整个项目的结构如下(mandarin.dat文件从xpinyin模块对应的文件夹下复制过来):
切换至该文件夹,输入以下命令即可生成exe文件:
1
|
pyinstaller - f poem_jielong.py
|
本项目的诗歌接龙有两种模式,一种为人工接龙,就是你先输入一句诗或一个字,然后就是计算机回复一句,你回复一句,负责诗歌接龙的规则;另一种模式为机器接龙,就是你先输入一句诗或一个字,机器会自动输出后面的接龙诗句(最多10个)。
先测试人工接龙模式:
再测试机器接龙模式:
总结
该项目的github地址为:https://github.com/percent4/shicijielong
原文链接:https://www.cnblogs.com/jclian91/p/9813142.html