Python爬取成語接龍類網(wǎng)站
介紹
本文將展示如何利用Python爬蟲來實現(xiàn)詩歌接龍。
該項目的思路如下:
利用爬蟲爬取詩歌,制作詩歌語料庫;
將詩歌分句,形成字典:鍵(key)為該句首字的拼音,值(value)為該拼音對應(yīng)的詩句,并將字典保存為pickle文件;
讀取pickle文件,編寫程序,以exe文件形式運行該程序。
該項目實現(xiàn)的詩歌接龍,規(guī)則為下一句的首字與上一句的尾字的拼音(包括聲調(diào))一致。下面將分步講述該項目的實現(xiàn)過程。
詩歌語料庫
首先,我們利用Python爬蟲來爬取詩歌,制作語料庫。爬取的網(wǎng)址為:https://www.gushiwen.org,頁面如下:

由于本文主要為試了展示該項目的思路,因此,只爬取了該頁面中的唐詩三百首、古詩三百、宋詞三百、宋詞精選,一共大約1100多首詩歌。為了加速爬蟲,采用并發(fā)實現(xiàn)爬蟲,并保存到poem.txt文件。完整的Python程序如下:
import re
import requests
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED
# 爬取的詩歌網(wǎng)址
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 = []
# 詩歌的網(wǎng)址
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)
# 利用并發(fā)爬取
executor = ThreadPoolExecutor(max_workers=10) # 可以自己調(diào)整max_workers,即線程的個數(shù)
# submit()的參數(shù): 第一個為函數(shù), 之后為該函數(shù)的傳入?yún)?shù),允許有多個
future_tasks = [executor.submit(get_poem, url) for url in poem_links]
# 等待所有的線程完成,才進入后續(xù)的執(zhí)行
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文件,形成我們的詩歌語料庫。當然,這些詩歌并不能直接使用,需要清理數(shù)據(jù),比如有些詩歌標點不規(guī)范,有些并不是詩歌,只是詩歌的序等等,這個過程需要人工操作,雖然稍顯麻煩,但為了后面的詩歌分句效果,也是值得的。
詩歌分句
有了詩歌語料庫,我們需要對詩歌進行分句,分句的標準為:按照結(jié)尾為。?!進行分句,這可以用正則表達式實現(xiàn)。之后,將分句好的詩歌寫成字典:鍵(key)為該句首字的拼音,值(value)為該拼音對應(yīng)的詩句,并將字典保存為pickle文件。完整的Python代碼如下:
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)的內(nèi)容:

當然,一個拼音可以對應(yīng)多個詩歌。
詩歌接龍
讀取pickle文件,編寫程序,以exe文件形式運行該程序。
為了能夠在編譯形成exe文件的時候不出錯,我們需要改寫xpinyin模塊的_init_.py文件,將該文件的全部代碼復(fù)制至mypinyin.py,并將代碼中的下面這句代碼
data_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'Mandarin.dat')
改寫為
data_path = os.path.join(os.getcwd(), 'Mandarin.dat')
這樣我們就完成了mypinyin.py文件。
接下來,我們需要編寫詩歌接龍的代碼(Poem_Jielong.py),完整代碼如下:
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)
# 設(shè)置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機器回復(fù):%s'%random.sample(poem_dict[tail], 1)[0], random.sample(color_list, 1)[0])
enter = str(input('你的回復(fù):'))[:-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 機器接龍): '))
現(xiàn)在整個項目的結(jié)構(gòu)如下(Mandarin.dat文件從xpinyin模塊對應(yīng)的文件夾下復(fù)制過來):

切換至該文件夾,輸入以下命令即可生成exe文件:
pyinstaller -F Poem_jielong.py

本項目的詩歌接龍有兩種模式,一種為人工接龍,就是你先輸入一句詩或一個字,然后就是計算機回復(fù)一句,你回復(fù)一句,負責(zé)詩歌接龍的規(guī)則;另一種模式為機器接龍,就是你先輸入一句詩或一個字,機器會自動輸出后面的接龍詩句(最多10個)。
先測試人工接龍模式:

再測試機器接龍模式:

總結(jié)
該項目的Github地址為:https://github.com/percent4/Shicijielong
相關(guān)文章
python中DataFrame數(shù)據(jù)合并merge()和concat()方法詳解
Pandas提供了很多合并Series和Dataframe的強大的功能,通過這些功能可以方便的進行數(shù)據(jù)分析,下面這篇文章主要給大家介紹了關(guān)于python中DataFrame數(shù)據(jù)合并merge()和concat()方法的相關(guān)資料,需要的朋友可以參考下2022-07-07
舉例講解Python中的list列表數(shù)據(jù)結(jié)構(gòu)用法
這篇文章主要介紹了Python中的list列表數(shù)據(jù)結(jié)構(gòu)用法,列表是Python內(nèi)置的六種集合類數(shù)據(jù)類型中最常見的之一,需要的朋友可以參考下2016-03-03
Python深度學(xué)習(xí)pytorch神經(jīng)網(wǎng)絡(luò)填充和步幅的理解
這篇文章主要介紹了Python深度學(xué)習(xí)pytorch神經(jīng)網(wǎng)絡(luò)填充和步幅的理解2021-10-10
基于pandas數(shù)據(jù)清洗的實現(xiàn)示例
數(shù)據(jù)清洗是數(shù)據(jù)科學(xué)和數(shù)據(jù)分析中非常重要的一個步驟,本文主要介紹了基于pandas的數(shù)據(jù)清洗,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-07-07

