??本文將介紹一個(gè)筆者自己的項(xiàng)目:自制簡(jiǎn)單的詩歌搜索系統(tǒng)。該系統(tǒng)主要的實(shí)現(xiàn)功能如下:指定一個(gè)關(guān)鍵詞,檢索出包含這個(gè)關(guān)鍵詞的詩歌,比如關(guān)鍵詞為“白云”,則檢索出的詩歌可以為王維的《送別》,內(nèi)容為“下馬飲君酒,問君何所之?君言不得意,歸臥南山陲。但去莫復(fù)問,白云無盡時(shí)?!?br>??該項(xiàng)目使用的Python模塊為:
requests
BeautifulSoup
pymongo
tornado
其中,requests模塊和BeautifulSoup模塊用來制作爬蟲,爬取網(wǎng)上的詩歌。pymongo模塊用來將爬取的詩歌寫入到MongoDB數(shù)據(jù)庫。tornado模塊用于網(wǎng)頁端展示。
??該項(xiàng)目主要分以下三步實(shí)現(xiàn):
收集數(shù)據(jù):使用爬蟲,爬取網(wǎng)上的詩歌作為項(xiàng)目的數(shù)據(jù)集;
存入數(shù)據(jù)庫:將爬取到的詩歌寫入到MongoDB數(shù)據(jù)庫;
網(wǎng)頁展示:利用tornado框架實(shí)現(xiàn)詩歌搜索功能。
該項(xiàng)目的結(jié)構(gòu)如下:
??首先,我們利用Python爬蟲來爬取詩歌,存為CSV文件poem.csv。爬取的網(wǎng)址為:https://www.gushiwen.org 。由于僅是展示該項(xiàng)目的思路,因此,只爬取了該頁面中的唐詩三百首、古詩三百、宋詞三百、宋詞精選,一共大約1100多首詩歌。
??實(shí)現(xiàn)該爬蟲的代碼文件為poem_scrape.py,代碼如下:
# -*- coding: utf-8 -*-import reimport requestsfrom bs4 import BeautifulSoupimport pandas as pd# 爬取的詩歌網(wǎng)址urls = ['https://www.gushiwen.org/gushi/tangshi.aspx', 'https://www.gushiwen.org/gushi/sanbai.aspx', 'https://www.gushiwen.org/gushi/songsan.aspx', 'https://www.gushiwen.org/gushi/songci.aspx' ]poem_links = []# 詩歌的網(wǎng)址for url in urls: # 請(qǐng)求頭部 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(link['href'])# print(poem_links)# print(len(poem_links))content_list = []title_list = []dynasty_list = []poet_list = []# 爬取詩歌頁面def get_poem(url): #url = 'https://so.gushiwen.org/shiwenv_45c396367f59.aspx' # 請(qǐng)求頭部 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") # 詩歌內(nèi)容 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('?', '?').replace('\n', '') content = poem if content: content_list.append(content) else: content_list.append('') # 詩歌朝代,詩人 dynasty_poet = soup.find('p', class_='source').text if ':' in dynasty_poet: dynasty, poet = dynasty_poet.split(':') else: dynasty, poet = '', '' dynasty_list.append(dynasty) poet_list.append(poet) # 詩歌標(biāo)題 title = soup.find('h1').text if title: title_list.append(title) else: title_list.append('')# 爬取詩歌for url in poem_links: get_poem(url)# 寫入至csv文件df = pd.DataFrame({'title': title_list, 'dynasty': dynasty_list, 'poet': poet_list, 'content': content_list })print(df.head())df.to_csv('./poem.csv', index=False)
儲(chǔ)存的poem.csv的前幾行如下:
??數(shù)據(jù)收集完畢后,我們需要將這些數(shù)據(jù)出訪到數(shù)據(jù)庫中,便于后續(xù)的調(diào)用,在這里選擇MongoDB。利用文件write2mongodb.py文件可以將剛才爬取到的詩歌存放至MongoDB數(shù)據(jù)庫中,完整的代碼如下:
import pandas as pdfrom pymongo import MongoClient# 連接MongoDBconn = MongoClient('mongodb://localhost:27017/')db = conn["test"]# 插入詩歌df = pd.read_csv('poem.csv')columns = ['title', 'dynasty', 'poet', 'content']for i in range(df.shape[0]): print(i) row = df.iloc[i, :] db.poem.insert(dict(zip(columns, row[columns])))
??不到一分鐘,我們可以看到MongoDB中的內(nèi)容如下:
??準(zhǔn)備好數(shù)據(jù)集后,我們需要可視化地展示詩歌檢索功能,我們選擇tornado這個(gè)框架來實(shí)現(xiàn)。詩歌檢索功能為:指定一個(gè)關(guān)鍵詞,檢索出包含這個(gè)關(guān)鍵詞的詩歌。關(guān)鍵詞由用戶輸入,提交HTTP請(qǐng)求,在后臺(tái)實(shí)現(xiàn)詩歌檢索功能,然后在前端頁面展示出來。
??實(shí)現(xiàn)的server.py的代碼如下:
# -*- coding: utf-8 -*-import randomimport os.pathimport tornado.httpserverimport tornado.ioloopimport tornado.optionsimport tornado.webfrom tornado.options import define, optionsfrom pymongo import MongoClient# 連接MongoDBconn = MongoClient('mongodb://localhost:27017/')coll = conn["test"].poem#定義端口為8000define("port", default=8000, help="run on the given port", type=int)# GET請(qǐng)求class QueryHandler(tornado.web.RequestHandler): # get函數(shù) def get(self): self.render('query.html')# POST請(qǐng)求# POST請(qǐng)求參數(shù):query_stringclass ResultHandler(tornado.web.RequestHandler): # post函數(shù) def post(self): query = self.get_argument('query_string') res = list(coll.find({'content': {'$regex': query}})) if len(res) > 0: result = random.sample(res, 1)[0] del result["_id"] title = result['title'] dynasty = result['dynasty'] poet = result['poet'] content = result['content'] else: title = '' dynasty = '' poet = '' content = '' self.render('result.html', query=query, title=title, dynasty=dynasty, poet=poet, content=content)# 主函數(shù)def main(): tornado.options.parse_command_line() # 定義app app = tornado.web.Application( handlers=[(r'/query', QueryHandler), (r'/result', ResultHandler)], #網(wǎng)頁路徑控制 template_path=os.path.join(os.path.dirname(__file__), "templates") # 模板路徑 ) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()main()
其中,query路徑對(duì)應(yīng)的網(wǎng)頁query.html的代碼如下:
<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>Poem Query</title></head><body><h2>請(qǐng)輸入查詢</h2><form method="post" action="/result"><p>包含文字: <input type="text" name="query_string"></p><input type="submit"></form></body></html>
result路徑對(duì)應(yīng)的網(wǎng)頁result.html如下:
<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>Result</title> <script>//highlight query word in the pagefunction Func(){var query = document.getElementById("query").innerHTML;query = query.split(':')[1];if(query == ''){alert('查詢?cè)~為空!')}else{ document.getElementById("result").innerHTML = document.getElementById("result").innerHTML.replace(new RegExp(query,'g'),'<mark>'+query+'</mark>');}}</script></head><body><font color="red"><p id="query">查詢?cè)~:{{query}}</p></font><p>標(biāo)題:{{title}}</p><p>朝代:{{dynasty}}</p><p>詩人:{{poet}}</p><p id="result">內(nèi)容:{{content}}</p><a href="/query"><button type="button">返回</button></a><button type="button" onclick="Func()">查詢?cè)~高亮</button></body>
??運(yùn)行server.py, 在瀏覽器中輸入網(wǎng)址:http://localhost:8000/query ,界面如下:
在其中輸入搜索關(guān)鍵詞,比如“白云”,則會(huì)顯示一條隨機(jī)的結(jié)果,如下:
點(diǎn)擊“查詢?cè)~高亮”,則查詢?cè)~部分會(huì)高亮顯示。
??本項(xiàng)目?jī)H為展示詩歌檢索的一種實(shí)現(xiàn)思路,仍有許多功能還待完善,后續(xù)將進(jìn)一步補(bǔ)充實(shí)現(xiàn)。
注意:本人現(xiàn)已開通微信公眾號(hào): Python爬蟲與算法
聯(lián)系客服