爬取唐詩宋詞生成詞雲


Python 高並發線程爬取詩詞之詩詞分析

本節所講內容:

1、5分鍾快速了解爬蟲概念

2、beautifulsoup 匹配原則

3、wordcloud 使用詳情

實戰:爬取中國唐詩宋詞,體驗文人雅士最常用的詞語!

 

1、5分鍾快速了解爬蟲

爬蟲(spider:網絡蜘蛛):是一個用腳本代替瀏覽器請求服務器獲取服務器資源的程序。

 

數據收集(數據分析、人工智能)

模擬操作(測試、數據采集)

接口操作(自動化)

爬蟲的原理:

              說到底,我們的爬蟲是模擬web請求,不論學習什么框架我們都需要對http協議的請求和響應有所了解:

        

         簡單的了解一下這幅圖。

2、beautifulsoup 匹配原則

如果一個正則匹配稍有差池,那可能程序就處在永久的循環之中,而且有的小伙伴們也對寫正則表達式的寫法用得不熟練,沒關系,我們還有一個更強大的工具,叫Beautiful Soup,有了它我們可以很方便地提取出HTML或XML標簽中的內容,實在是方便,這一節就讓我們一起來感受一下Beautiful Soup的強大吧。

什么是Beautiful Soup

簡單來說,Beautiful Soup是python的一個庫,最主要的功能是從網頁抓取數據。

官方解釋如下:

Beautiful Soup提供一些簡單的、python式的函數用來處理導航、搜索、修改分析樹等功能。它是一個工具箱,通過解析文檔為用戶提供需要抓取的數據,因為簡單,所以不需要多少代碼就可以寫出一個完整的應用程序。

2.1 bs的安裝

環境介紹: pycharm 2017.2.3 + python 3.5.0

       Pip install bs4

首先必須要導入 bs4 庫, 創建BeautifulSoup對象

from bs4 import BeautifulSoup as BS
text = '''
<html>
<head>
    <meta = charset='UTF-8' >
    <title id =1 href = 'http://example.com/elsie' class = 'title'>Test</title>
</head>
<body>
   <div class = 'ok'>
       <div class = 'nice'>
           <p class = 'p'>
               Hello World
           </p>
            <p class = 'e'>
              
風一般的男人
           </p>
       </div>
   </div>
</body>
</html>
'''
soup = BS(text,"lxml")#前面是要解析的內容,后面是指定的解析器
print(soup.prettify())#轉換字符串
print(type(soup.prettify()))
print(type(soup))

2.2.2  搜索文檔樹

find()和find_all()

find_all()方法搜索當前tag的所有tag子節點,並判斷是否符合過濾器的條件。

find()和find_all()的區別就是,find直接返回元素的一個結果,find_all返回元素列表

find_all( name , attrs , recursive , text , **kwargs )簡介一下參數

name 參數可以查找所有名字為name的tag,字符串對象會被自動忽略掉;name參數可以傳入字符串、正則表達式、列表、True、自定義的方法等但是各自代表的含義不一樣。

字符串,在搜索方法中傳入一個字符串參數,Beautiful Soup會查找與字符串完整匹配的內容。

print(soup.find('body'))
print(soup.find_all('body')

如果匹配成功將會匹配所有的tag

如果一個指定名字的參數不是搜索內置的一些參數名,搜索時會把該參數當作指定名字tag的屬性來

搜索;例如id=1

如果包含一個名字為 id 的參數,Beautiful Soup會搜索每個tag的”id”屬性;

如果傳入 href 參數,Beautiful Soup會搜索每個tag的”href”屬性;

使用多個指定名字的參數可以同時過濾tag的多個屬性;

對於class ,可以使用class_來搜索

#返回這個class=‘p’的標簽內容。

print(soup.find_all('p',class_='p'))

對於某些tag屬性不能通過搜索得到值,可以使用attrs參數得到

#返回class為e的標簽

print(soup.find_all(attrs={'class':'e'}))

3、wordcloud 使用詳情

wordcloud 簡單利用英語來看就是詞雲,它是以詞語為基本單位,更加直觀的展示出我們的內容。

wordcloud 的安裝

pip install wordcloud

大家順便安裝下:pip install jieba

1、基本格式
#導入詞雲
from wordcloud import WordCloud
#打開文件並且讀取完全
f = open('1.txt','r').read()
#創建wc設個實例對象,里面可傳遞相應的參數
#generate根據文本生成詞雲
wc = WordCloud(
   
background_color='white',
   
width=500,
   
height=366,
   
margin=2
).generate(f)
#to_file 輸出到文件
wc.to_file('./image/0.jpg')

3、wordcloud 使用詳情

wordcloud 簡單利用英語來看就是詞雲,它是以詞語為基本單位,更加直觀的展示出我們的內容。

wordcloud 的安裝

pip install wordcloud

大家順便安裝下:pip install jieba

1、基本格式
#導入詞雲
from wordcloud import WordCloud
#打開文件並且讀取完全
f = open('1.txt','r').read()
#創建wc設個實例對象,里面可傳遞相應的參數
#generate根據文本生成詞雲
wc = WordCloud(
   
background_color='white',
   
width=500,
   
height=366,
   
margin=2
).generate(f)
#to_file 輸出到文件
wc.to_file('./image/0.jpg')
 
        

實戰:爬取中國唐詩宋詞,體驗文人雅士最常用的詞語!

第一步:下載中國的唐詩宋詞

第二步:把數據保存到本地

第三步:結巴分詞

第四步:生成詞雲簡單分析

代碼如下:

下載唐詩宋詞保存本地

# -*- coding: utf-8 -*-
# @Time    : 2019/2/25 10:23
# @Author  : for
# @File    : test01.py
# @Software: PyCharm
import re
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED
#這是url地址
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'
       
]
#處理獲取每個詩詞的url地址
poem_links = []
for url in urls:
   
# 請求頭部
   
ua = UserAgent()
    headers = {
'User-Agent': ua.random}
    req = requests.get(url,
headers=headers)
   
#把爬取到的文本格式改成bs4可改變的格式
   
soup = BeautifulSoup(req.text, "lxml")
   
#定位到第一個class = sone的內容
   
content = soup.find_all('div', class_="sons")[0]
   
#獲取該content 下所有a標簽
   
links = content.find_all('a')
   
print(links)
   
#進行比遍歷,url地址拼接
   
for link in links:
        poem_links.append(
'https://so.gushiwen.org'+link['href'])

poem_list = []
def get_poem(url):
   
# 請求頭部
   
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))
print(poems)
for poem in poems:
    poem = poem.replace(
'《','').replace('》','').replace(':', '').replace('“', '')
   
print(poem)
   
with open('poem.txt', 'a',encoding='utf-8') as f:
        f.write(poem)
        f.write(
'\n')

結果展示:

 

生成詞雲進行分析:
import jieba
from wordcloud import WordCloud,STOPWORDS
wc = WordCloud(
background_color='white'# 背景顏色
              
max_words=1000# 最大詞數
               # mask=back_color,  # 以該參數值作圖繪制詞雲,這個參數不為空時,width和height會被忽略
              
max_font_size=100# 顯示字體的最大值
              
stopwords=STOPWORDS.add('國'),  # 使用內置的屏蔽詞,再添加'苟利國'
               # font_path="C:/Windows/Fonts/STFANGSO.ttf",  # 解決顯示口字型亂碼問題,可進入C:/Windows/Fonts/目錄更換字體
              
font_path='C:\Windows\Fonts\simfang.ttf',
              
random_state=42# 為每個詞返回一個PIL顏色
               # width=1000,  # 圖片的寬
               # height=860  #圖片的長
              
)
text =
open('poem.txt').read()
# 該函數的作用就是把屏蔽詞去掉,使用這個函數就不用在WordCloud參數中添加stopwords參數了
# 把你需要屏蔽的詞全部放入一個stopwords文本文件里即可
def stop_words(texts):
    words_list = []
    word_generator = jieba.cut(texts,
cut_all=False# 返回的是一個迭代器
   
for word in word_generator:
        words_list.append(word)
   
print(words_list)
   
return ' '.join(words_list)  # 注意是空格
text = stop_words(text)
wc.generate(text)
# 顯示圖片
wc.to_file('maikou.png')

效果展示

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM