在 句子迷 爬取網友總結的方文山歌詞並作詞頻統計

2021-08-19 11:24:03 字數 2556 閱讀 8281

要求:

1. 選乙個自己感興趣的主題。

2. 用python 編寫爬蟲程式,從網路上爬取相關主題的資料。

3. 對爬了的資料進行文字分析,生成詞云。

4. 對文字分析結果進行解釋說明。

5. 寫一篇完整的部落格,描述上述實現過程、遇到的問題及解決辦法、資料分析思想及結論。

6. 最後提交爬取的全部資料、爬蟲及資料分析源**。

在此次作業中,我通過爬取**『句子迷』中方文山的歌詞片段來看其作詞中詞頻以及網友較為喜歡方老師那些句子。

在爬取的過程中主要遇到的問題是該**對於請求過來的headers有做檢查,所以需要加入headers引數,宣告ua

**如下:

import jieba

import requests

from bs4 import beautifulsoup

lyrics = ''

headers =

resp = requests.get('', headers=headers)

resp.encoding = 'utf-8'

print(resp.status_code)

soup = beautifulsoup(resp.text, 'html.parser')

page_url = '?page={}'

page_last = soup.select('.pager-last')

if len(page_last) > 0:

page_last = page_last[0].text

for i in range(0, int(page_last)):

print(i)

resp = requests.get(page_url.format(i), headers=headers)

resp.encoding = 'utf-8'

soup = beautifulsoup(resp.text, 'html.parser')

for a in soup.select('.xlistju'):

lyrics += a.text + ' '

# 保留爬取的句子

with open('lyrics.txt', 'a+', encoding='utf-8') as lyricfile:

lyricfile.write(lyrics)

# 載入標點符號並去除歌詞中的標點

with open('punctuation.txt', 'r', encoding='utf-8') as punctuationfile:

for punctuation in punctuationfile.readlines():

lyrics = lyrics.replace(punctuation[0], ' ')

# 載入無意義詞彙

with open('meaningless.txt', 'r', encoding='utf-8') as meaninglessfile:

mlessset = set(meaninglessfile.read().split('\n'))

mlessset.add(' ')

# 載入保留字

with open('reservedword.txt', 'r', encoding='utf-8') as reservedwordfile:

reservedwordset = set(reservedwordfile.read().split('\n'))

for reservedword in reservedwordset:

jieba.add_word(reservedword)

keywordlist = list(jieba.cut(lyrics))

keywordset = set(keywordlist) - mlessset # 將無意義詞從詞語集合中刪除

keyworddict = {}

# 統計出詞頻字典

for word in keywordset:

keyworddict[word] = keywordlist.count(word)

# 對詞頻進行排序

keywordlistsorted = list(keyworddict.items())

keywordlistsorted.sort(key=lambda e: e[1], reverse=true)

# 將所有詞頻寫出到txt

for topwordtup in keywordlistsorted:

print(topwordtup)

with open('word.txt', 'a+', encoding='utf-8') as wordfile:

for i in range(0, topwordtup[1]):

wordfile.write(topwordtup[0]+'\n')

上面的**生成的word.txt中,將詞彙複製到**做詞云生成,生成後的詞雲圖如下:

校花網爬取

聯絡爬蟲使用 1 堆糖校花網api 獲取資料的api 路徑 path 2 簡要介紹爬蟲 2 從解析過程來說 方式2 模擬瀏覽器傳送請求 獲取網頁 提取有用的資料 存放於資料庫或檔案中 爬蟲要做的就是方式2 爬蟲過程圖 3 過程各個階段的主要介紹 1 發起請求 使用http庫向目標站點發起請求,即傳送...

爬取豆瓣網電影資訊

coding utf 8 import urllib2 import bs4 from bs4 import beautifulsoup 爬取豆瓣網電影簡介,包括電影名,導演,評分以及介紹等 class dbtop def init self self.usr agent mozilla 5.0 w...

Python爬取散文網散文

配置python 2.7 bs4 requests 安裝 用pip進行安裝 sudo pip install bs4 sudo pip install requests 簡要說明一下bs4的使用因為是爬取網頁 所以就介紹find 跟find all find跟find all的不同在於返回的東西不同...