宣告:此文並不是標題黨,如果你不滿18歲,請馬上關閉,在父母陪同下觀看也不行。
資料來源
本文的資料抓取自國內最大的亞文化視訊社群網站(不,不是 B 站),其中使用者出於各種目的會在發帖的標題中加入城市名稱,於是本文抓取了前10000個帖子的標題和發帖使用者 ID,由於按照最近發帖的順序排列,所以抓取資料基本上涵蓋了2016年期間的發帖內容。然後通過匹配提取標題中所包含的城市資訊,對16年活躍使用者的歸屬地進行分析統計,另根據最近釋出的《2016年中國主要城市 GDP 排名》:
檢驗兩者之間是否存在某種程度的相關。
爬蟲
當然本文的目的主要還是出於純粹的技術討論與實踐,資料抓取和分析處理均使用 Python 完成,其中主要用到的資料處理和視覺化工具包分別是Pandas和Plot.ly+Pandas。
由於網站使用較傳統的論壇框架,經測試也沒有防爬蟲的措施,因此可以大膽地使用多執行緒,對於網頁內容分析也可以直接用正則匹配完成:
import requests as req
import re
from threading import Thread
def parser(url):
res = req.get(url)
html = res.text.encode(res.encoding).decode()
titles = re.findall(RE_TITLE, html)
v = []
if titles is not None:
for title in titles:
if len(title) == 2 and title[-1] != 'admin':
if title[0][-1] != '>':
v.append(title)
return v
def worker(rag):
"""
將每個執行緒的資料臨時儲存到一個新的文字檔案中即可。
"""
with open('{}+{}.txt'.format(*rag), 'w+') as result:
for p in range(*rag):
url = ENT_PAT.format(p)
for title in parser(url):
result.write("{}|{}\n".format(*title))
def main():
threads = []
for i in range(len(SECTIONS)-1):
threads.append(Thread(target=worker, args=(SECTIONS[i:i+2],)))
for thr in threads:
thr.start()
if __name__ == '__main__':
main()複製程式碼
以上就是爬蟲部分的程式碼(當然隱去了最關鍵的網址資訊,當然這對老司機們來說並不是問題)。
Pandas
Pandas 可以看做是在 Python 中用於儲存、處理資料的 Excel,與 R 語言中的 data.frame 的概念相似。首先將所有單獨儲存的檔案中的資料匯入到 Pandas:
import os
import pandas as pd
title, user = [], []
for root, _, filenames in os.walk('raws'):
for f in filenames:
with open(os.path.join(root, f), 'r') as txt:
for line in txt.readlines():
if line and len(line.split("|")) == 2:
t, u = line.split("|")
title.append(t)
user.append(u.strip())
data = pd.DataFrame({"title": title, "user": user})
# 儲存到 csv 檔案備用
data.to_csv("91.csv", index=False)複製程式碼
接下來以同樣的方式將國內主要城市資料、2016主要城市 GDP 排行資料載入到 Pandas 中備用。
資料分析
首先需要明確以目前的資料可以探討哪些有趣的問題:
- 各個城市的發帖總數;
- 各個城市的活躍使用者數量;
- 以上兩個資料結果與 GDP 之間的關係;
- 發帖形式分類(雖然這個問題的答案可能更有趣,以目前的資料量很難回答這問題,而且需要涉及到較複雜的 NLP,先寫在這裡);
- 最活躍的使用者來自哪裡。
首先載入備用的資料:
import pandas as pd
TABLE_POSTS = pd.read_csv("91.csv")
TABLE_CITY = pd.read_csv("TABLE_CITY.csv")
TABLE_GDP = pd.read_csv("TABLE_GDP.csv")複製程式碼
匹配標題中是否存在城市的名稱:
# 先替換可能出現的“暱稱”
TABLE_POSTS.title = TABLE_POSTS.title.str.replace("帝都", "北京")
TABLE_POSTS.title = TABLE_POSTS.title.str.replace("魔都", "上海")
def query_city(title):
for city in TABLE_CITY.city:
if city in title:
return city
return 'No_CITY'
TABLE_POSTS['city'] = TABLE_POSTS.apply(
lambda row: query_city(row.title),
axis=1)
# 過濾掉沒有出現城市名的資料:
posts_with_city = TABLE_POSTS.loc[TABLE_POSTS.city != 'No_CITY']
# 以城市名進行 groupby,並按發帖數之和倒序排列:
posts_with_city_by_posts = posts_with_city.groupby(by="city").count().sort_values("title", ascending=False)[['title']].head(20)複製程式碼
現在已經可以直接回答第一個問題了,用 Plot.ly 將 Pandas 中的資料視覺化出來,有兩種方式,我們選擇較簡單的 cufflinks 庫,直接在 DataFrame 中繪製:
import cufflinks as cf
cf.set_config_file(world_readable=False,offline=True)
posts_with_city_by_posts.head(10).iplot(kind='pie',
labels='city',
values='title',
textinfo='label+percent',
colorscale='Spectral',
layout=dict(
title="City / Posts",
width="500",
xaxis1=None,
yaxis1=None))複製程式碼
前6名基本上不出什麼意外,但是大山東排在第7名,這就有點意思了。
為了排除某些“特別活躍”使用者的干擾,將使用者重複發帖的情況去除,只看發帖使用者數量:
# 去除 user 欄中的重複資料
uniq_user = posts_with_city.drop_duplicates('user')
# 同樣按照城市 groupby,然後倒序排列
posts_with_city_by_user = uniq_user.groupby(by="city").count().sort_values("title", ascending=False)[['title']].head(15)
posts_with_city_by_user.head(10).iplot(kind='pie',
values='title',
labels='city',
textinfo='percent+label',
colorscale='Spectral',
layout=dict(title="City / Users",
width="500",
xaxis1=None,
yaxis1=None))複製程式碼
Impressive,山東。至少說明還是比較含蓄,不太願意寫明具體的城市?是這樣嗎,這個問題可以在最後一個問題的答案中找到一些端倪。
接下來要和 GDP 資料整合到一起,相當於將兩個 DataFrame 以城市名為鍵 join 起來:
posts_with_city_by_user_and_gdp = posts_with_city_by_user.merge(TABLE_GDP, left_on='city', right_on='city', how='inner')複製程式碼
由於有些漏掉的排行資料,同時由於人口資料較大,需要進行一定的預處理和標準化處理:
posts_with_city_by_user_and_gdp['norm_title'] = \
posts_with_city_by_user_and_gdp.title/posts_with_city_by_user_and_gdp['pop']
posts_with_city_by_user_and_gdp['norm_rank'] = \
posts_with_city_by_user_and_gdp['rank'].rank()
posts_with_city_by_user_and_gdp['x'] =
posts_with_city_by_user_and_gdp.index.max() - posts_with_city_by_user_and_gdp.index + 1
posts_with_city_by_user_and_gdp['y'] =
posts_with_city_by_user_and_gdp['norm_rank'].max() - posts_with_city_by_user_and_gdp['norm_rank'] + 1複製程式碼
繪製氣泡圖,氣泡大小為使用者數量與人口數的比,座標值越大排行越高:
可以看到基本上存在一定程度的相關,但是到這裡我們發現更有趣的資料應該是那些出現在 GDP 排行榜上卻沒有出現在網站排行上的城市,是不是說明這些城市更加勤勞質樸,心無旁騖地擼起袖子幹呢?
good_cities = posts_with_city_by_user.merge(TABLE_GDP, left_o
="city", right_on="city", how="right")
good_cities[list(good_cities.title.isnull())][['city', 'rank', 'pop', 'title']]複製程式碼
注:由於 posts_with_city_by_user 只擷取了前15,實際上青島是排在前20的,從下一個結果中就能看出來…
最後一個問題,最活躍的老司機們都來自哪個城市?
user_rank = pd.DataFrame(TABLE_POSTS.user.value_counts().head(20))
user_rank.reset_index(level=0, inplace=True)
user_rank.columns = ['user', 'count']
user_rank.merge(posts_with_city[['user', 'city']], left_on='user', right_on='user', how='inner').drop_duplicates(['user','city'])複製程式碼
總結
以上就是全部資料與分析的結果。其實大部分只是一個直觀的結果展示,既沒有嚴謹的統計分析,也沒有過度引申的解讀。只有經過統計檢驗才能得出擁有可信度的結論,在一開始已經說明了本文只是純粹的技術討論與實踐,所抓取的10000多條資料也只是網站中某個板塊,因此對於以上結果不必太過認真。
再來說說 Pandas 與 R 語言的 data.frame 之間的比較,其共同點在於都是基於資料框架的設計,擁有大量常用的資料操作方法、工具以及第三方支援的庫(包括視覺化),資料處理過程大部分不需要通過“迴圈語句”,只需要對資料整體進行操作即可;不同之處在於基於 Python 的 Pandas 更像是物件導向或者面向方法的,而 data.frame 則更像是面相資料的,如果是針對純粹的資料(例如實驗資料),兩者的使用體驗幾乎是一致的,但是如果存在較多文字資料(例如本文),以我的個人經驗還是 Python 更勝一籌。