成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

自制簡單的詩歌搜索系統(tǒng)

SegmentFault / 3229人閱讀

摘要:項目簡介本文將介紹一個筆者自己的項目自制簡單的詩歌搜索系統(tǒng)。該項目使用的模塊為其中,模塊和模塊用來制作爬蟲,爬取網(wǎng)上的詩歌。

項目簡介

??本文將介紹一個筆者自己的項目:自制簡單的詩歌搜索系統(tǒng)。該系統(tǒng)主要的實現(xiàn)功能如下:指定一個關(guān)鍵詞,檢索出包含這個關(guān)鍵詞的詩歌,比如關(guān)鍵詞為“白云”,則檢索出的詩歌可以為王維的《送別》,內(nèi)容為“下馬飲君酒,問君何所之?君言不得意,歸臥南山陲。但去莫復(fù)問,白云無盡時?!?br>??該項目使用的Python模塊為:

requests

BeautifulSoup

pymongo

tornado

其中,requests模塊和BeautifulSoup模塊用來制作爬蟲,爬取網(wǎng)上的詩歌。pymongo模塊用來將爬取的詩歌寫入到MongoDB數(shù)據(jù)庫。tornado模塊用于網(wǎng)頁端展示。
??該項目主要分以下三步實現(xiàn):

收集數(shù)據(jù):使用爬蟲,爬取網(wǎng)上的詩歌作為項目的數(shù)據(jù)集;

存入數(shù)據(jù)庫:將爬取到的詩歌寫入到MongoDB數(shù)據(jù)庫;

網(wǎng)頁展示:利用tornado框架實現(xiàn)詩歌搜索功能。

該項目的結(jié)構(gòu)如下:

數(shù)據(jù)收集

??首先,我們利用Python爬蟲來爬取詩歌,存為CSV文件poem.csv。爬取的網(wǎng)址為:https://www.gushiwen.org 。由于僅是展示該項目的思路,因此,只爬取了該頁面中的唐詩三百首、古詩三百、宋詞三百、宋詞精選,一共大約1100多首詩歌。
??實現(xiàn)該爬蟲的代碼文件為poem_scrape.py,代碼如下:

# -*- coding: utf-8 -*-

import re
import requests
from bs4 import BeautifulSoup
import 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:
    # 請求頭部
    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"
    # 請求頭部
    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"([sS]*?)"), "", poem)
    poem = re.sub(re.compile(r"([sS]*?)"), "", poem)
    poem = re.sub(re.compile(r"。([sS]*?)"), "", poem)
    poem = poem.replace("!", "!").replace("?", "?").replace("
", "")
    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)

儲存的poem.csv的前幾行如下:

數(shù)據(jù)庫

??數(shù)據(jù)收集完畢后,我們需要將這些數(shù)據(jù)出訪到數(shù)據(jù)庫中,便于后續(xù)的調(diào)用,在這里選擇MongoDB。利用文件write2mongodb.py文件可以將剛才爬取到的詩歌存放至MongoDB數(shù)據(jù)庫中,完整的代碼如下:

import pandas as pd
from pymongo import MongoClient

# 連接MongoDB
conn = 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這個框架來實現(xiàn)。詩歌檢索功能為:指定一個關(guān)鍵詞,檢索出包含這個關(guān)鍵詞的詩歌。關(guān)鍵詞由用戶輸入,提交HTTP請求,在后臺實現(xiàn)詩歌檢索功能,然后在前端頁面展示出來。
??實現(xiàn)的server.py的代碼如下:

# -*- coding: utf-8 -*-

import random
import os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
from pymongo import MongoClient

# 連接MongoDB
conn = MongoClient("mongodb://localhost:27017/")
coll = conn["test"].poem

#定義端口為8000
define("port", default=8000, help="run on the given port", type=int)

# GET請求
class QueryHandler(tornado.web.RequestHandler):
    # get函數(shù)
    def get(self):
        self.render("query.html")

# POST請求
# POST請求參數(shù):query_string
class 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路徑對應(yīng)的網(wǎng)頁query.html的代碼如下:




    
    Poem Query


請輸入查詢

包含文字:

result路徑對應(yīng)的網(wǎng)頁result.html如下:




    
    Result
    


查詢詞:{{query}}

標(biāo)題:{{title}}

朝代:{{dynasty}}

詩人:{{poet}}

內(nèi)容:{{content}}

使用示例

??運行server.py, 在瀏覽器中輸入網(wǎng)址:http://localhost:8000/query ,界面如下:

在其中輸入搜索關(guān)鍵詞,比如“白云”,則會顯示一條隨機(jī)的結(jié)果,如下:

點擊“查詢詞高亮”,則查詢詞部分會高亮顯示。

總結(jié)

??本項目僅為展示詩歌檢索的一種實現(xiàn)思路,仍有許多功能還待完善,后續(xù)將進(jìn)一步補充實現(xiàn)。本項目的github地址為:https://github.com/percent4/P... 。

注意:本人現(xiàn)已開通微信公眾號: Python爬蟲與算法(微信號為:easy_web_scrape), 歡迎大家關(guān)注哦~~

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/43163.html

相關(guān)文章

  • Java爬蟲之利用Jsoup自制簡單搜索引擎

    摘要:的官方網(wǎng)址為,其使用手冊網(wǎng)址為本次分享將實現(xiàn)的功能為利用爬取某個搜索詞語暫僅限英文的百度百科的介紹部分,具體的功能介紹可以參考博客爬蟲自制簡單的搜索引擎。 ??Jsoup 是一款Java 的HTML解析器,可直接解析某個URL地址、HTML文本內(nèi)容。它提供了一套非常省力的API,可通過DOM,CSS以及類似于jQuery的操作方法來取出和操作數(shù)據(jù)。Jsoup的官方網(wǎng)址為: https:...

    GHOST_349178 評論0 收藏0
  • 優(yōu)雅使用WebMagic框架寫Java爬蟲

    摘要:優(yōu)雅的使用框架,爬取唐詩別苑網(wǎng)的詩人詩歌數(shù)據(jù)同時在幾種動態(tài)加載技術(shù)中對比作選擇雖然差不多兩年沒有維護(hù),但其本身是一個優(yōu)秀的爬蟲框架的實現(xiàn),源碼中有很多值得參考的地方,特別是對爬蟲多線程的控制。 優(yōu)雅的使用WebMagic框架,爬取唐詩別苑網(wǎng)的詩人詩歌數(shù)據(jù) 同時在幾種動態(tài)加載技術(shù)(HtmlUnit、PhantomJS、Selenium、JavaScriptEngine)中對比作選擇 We...

    leejan97 評論0 收藏0
  • Spring Boot入門(13)自制音樂平臺

    摘要:經(jīng)過筆者這幾天的辛勤勞作其實就是苦逼地碼代碼,一個新的網(wǎng)站已經(jīng)上線啦該網(wǎng)站是用工具寫的,主要實現(xiàn)的功能如下根據(jù)歌曲名稱和音樂平臺搜索歌曲,并實現(xiàn)歌曲的在線播放歌曲的下載功能網(wǎng)頁統(tǒng)計量功能開發(fā)歷史介紹。 ??經(jīng)過筆者這幾天的辛勤勞作(其實就是苦逼地碼代碼),一個新的網(wǎng)站已經(jīng)上線啦!該網(wǎng)站是用Spring Boot工具寫的,主要實現(xiàn)的功能如下: 根據(jù)歌曲名稱和音樂平臺搜索歌曲,并實現(xiàn)歌曲...

    Mr_zhang 評論0 收藏0
  • 用python自制微信機(jī)器人,定時發(fā)送天氣預(yù)報

    摘要:環(huán)境操作系統(tǒng)版本代碼實現(xiàn)我們要實現(xiàn)用來發(fā)微信,發(fā)送的內(nèi)容是每天最新的天氣信息。接下來就是登錄微信定時發(fā)送消息了。 showImg(https://segmentfault.com/img/remote/1460000018634433); 0 引言 前段時間找到了一個免費的天氣預(yù)報API,費了好段時間把這個API解析并組裝成自己想用的格式了,就想著如何實現(xiàn)每天發(fā)送天氣信息給自己。最近無...

    Turbo 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<