論如何知道一我的近年來關注了啥

任務背景:

爬取水木社區某位貼主在全部發帖版面的帖子,分析隨時間變化,貼主關注話題的變化。html

主要步驟:

1.爬取帖子

這部分的實現源碼存於「水木爬蟲」文件夾中,運行環境爲python3。python

1)獲取發帖版面:首先是spiderman_007.py,在代碼中可設置待爬的貼主id。以貼主VChart爲例,運行可獲得該貼主發帖的版面及該版面的頁數,記錄在文件中「VChart.txt」中,git

關鍵代碼:github

 1 # 查找發貼版面並記錄版面信息
 2 while page_num < url[topical]:
 3     content = get_url_content(now_url)
 4     page_num += 1
 5     page_str = str(page_num)
 6     now_url = base_url + page_str    # 構造爬蟲的網頁連接
 7     soup = BeautifulSoup(content, 'html.parser') # 用BeautifulSoup提取網頁中的文本內容
 8     i = 0
 9     name = 'VChart'
10     while i < 20:
11         # 查找標籤獲取貼主id
12         new_name = soup.find_all("li")[i].next_element.next_sibling.next_element.next_element.next_element
13         
14         # 若查找到一條記錄就記錄信息並跳出循環進行下一版面的查找
15         if new_name == name:
16             f.write("\'" + topical + "\'" + ": " + str(url[topical]) + ", ")
17             i = 21
18             page_num = url[topical] + 1
19         elif new_name is None:
20             i = 21
21     i += 1
View Code

部分截圖以下:正則表達式

2)爬取帖子:根據Vchart.txt中的信息,運行spiderman.py可獲得該貼主截至目前發佈的帖子,記錄在文件「VChart_texts.txt」中。算法

關鍵代碼:json

 1 # 爬取每一個版面的貼主的帖子並寫入文件
 2 now_url = base_url + page_str    # 構造爬蟲網頁連接
 3 soup = BeautifulSoup(content, 'html.parser')    # 使用BeautifulSoup提取網頁中的文本信息
 4 i = 0
 5 name = 'VChart'
 6 while i < 20:
 7     # 獲取每一頁全部的貼主id
 8     new_name = soup.find_all("li")[i].next_element.next_sibling.next_element.next_element.next_element
 9 
10     if new_name == name:
11         new_url = base_url_+soup.find_all("li")[i].next_element.next_element.get('href')
12         f.write(new_url)
13         f.write("\n")
14 
15         content_ = get_url_content(new_url)
16         soup1 = BeautifulSoup(content_, 'html.parser')
17         s = soup1.select(".sp")
18         f.write(s[2].previous_sibling()[0].get_text())
19         l = len(s)
20         j = 2
21         while j < l-2:
22             s1 = s[j].get_text()
23             j += 1
24             f.write(s1)
25         time.sleep(1)
26     i += 1
View Code

部分截圖以下:網絡

2.對帖子進行排序、分詞、聚類

1)排序:對帖子按時間進行排序,運行sort_data.py可得VCharttexts_sorted.txt,app

關鍵代碼:ide

 1 # 根據一段帖子文本中的時間信息排序,返回一個list
 2 def list_sort(list1):
 3     pattern = re.compile("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}")
 4 
 5     print(list1)
 6     list2 = re.findall(pattern, str(list1))
 7     list3 = list(zip(list2, list1))
 8     list3 = sorted(list3, key=lambda item: item[0])
 9     list4 = []
10     for temp in list3:
11         list4.append(temp[1])
12     return list4
View Code

部分截圖以下:

2)分詞:將帖子按必定時間段分爲不一樣文件,以每年爲一段爲例,該貼主的帖子發帖時間爲2004-2018年,共分爲15個文件存於文檔->VChart->time中,運行fenci_time.py能夠獲得每一段時間文檔的分詞及詞頻結果,存於time文件下。

關鍵代碼:

 1 # 分詞寫並寫入文件
 2 def segmented(file, text):
 3     ans = re.sub('[^\w\u4e00-\u9fff]+', "", text)  # 正則表達式過濾出漢字
 4     ans = "".join(ans.split())
 5     # seg_list = jieba.cut(ans)  # 精確模式(默認是精確模式)
 6     # print("[精確模式]: ", "/ ".join(seg_list))
 7     words = jieba.cut(ans, cut_all=False)
 8     word_freq = {}
 9     stopwords = stopwordslist('ting.txt')    # 去除停用詞
10     for word in words:
11         if word in word_freq:
12             word_freq[word] += 1
13         else:
14             word_freq[word] = 1
15 
16     freq_word = []
17     for word, freq in word_freq.items():
18         freq_word.append((word, freq))
19     freq_word.sort(key=lambda x: x[1], reverse=True)
View Code

3)分詞:運行fenlegeci.py能夠獲得對全部貼子進行分詞、排序並統計詞頻的文件「fencihou.txt」。

4)取出無用詞:將fencihou.txt文件中的內容複製到Excel中,須要手動刪去一些無心義和體現不出貼主發貼話題的詞,例如「中」「提到」「大做」「水木」等。

5)計算百分比:運行cout_frequency&percent.py能夠根據5)、6)中獲得的結果獲得每一個詞在每一個時間段的詞頻百分比,生成文件「統計.xls」。詞頻百分比=該詞的詞頻÷該時間段全部詞的詞頻總數×100%。

關鍵代碼:

1 # Excel文件讀寫操做
2 readbook = xlrd.open_workbook(r'統計_all.xlsx')
3 sheet = readbook.sheet_by_name('Sheet1')
4 nrows = sheet.nrows
5 f = xlwt.Workbook(encoding='utf-8')
6 table = f.add_sheet('data')
7 
8 table.write(i, j, 0)
9 f.save("統計.xls")
View Code

部分截圖以下:

6)生成.csv文件:在A1處填上「word」,將文件另存爲「VChart時間詞頻百分比.csv」,即存爲.csv格式的文件,注意編碼方式要選擇「UTF-8」。該文件能夠被用於在weka軟件中進行聚類。

7)聚類:打開weka->Explorer->Open file,選則打開6)中的csv文件。

選則Cluster,點擊Choose選則SimpleKmeans算法進行聚類。

點擊下圖紅框處能夠設置KMeans相關參數。選則「Classes to clusters evaluation」並按「word」聚類,點擊「Start」便可運行。

運行結束後,左下角會有運行記錄,右鍵選則Save result buffer能夠獲得結果文件。

爲了方便查看內容,推薦使用Notepad++打開文件。

8)獲取聚類結果:weka的運行結果文件中有不少用不到的信息,運行clustering文件夾下的get_class_words.py文件能夠獲得每一類的詞的信息,形式以下:

3.展現

對每一類詞隨時間變化的展現,主要參考了https://github.com/TangliziGit/ColumnsAnimation.git中的項目。

1)統計每一類詞的詞頻百分比在各個時間段內的平均值,用於展現。

2)使用ColumnsAnimation->data中的getdata.py能夠獲得本身的展現數據的data.json文件。

3)在data.json文件開頭添加「var TotalData=」並另存爲「data.js」放在ColumnsAnimation目錄下,打開animation.html便可看到展現效果。

例如,在2004年,各個話題的詞頻百分好比下:

在2005年,各個話題詞頻百分比變化爲:

這兩年裏,貼主的最關注的話題由「軍事科學」轉向「模擬飛行」。對軍事的愛好絲絕不減,只是轉向了虛擬空間。同時,增長了對軟件工程的關注度,與軟件工程相關的電腦設備等話題關注度也有所提升,而且一如既地關注網絡技術。

 

各話題詞頻變化統計展現至2018年,項目中的11-24.mp4爲效果錄屏文件,錄屏效果以下:

 由圖可看出從2004-2018年,隨時間變化,經過聚類獲得的貼主關注的10個話題的變化。

 

本項目地址:https://git.coding.net/Ruidxr/ShuiMu.git

相關文章
相關標籤/搜索