結(jié)果
結(jié)果統(tǒng)計1.png
結(jié)果統(tǒng)計2.png
代碼
# coding: utf-8
import pymongo
import charts
client = pymongo.MongoClient('localhost', 27017)
ganji = client['ganji']
item_info = ganji['item_info']
for i in item_info.find().limit(300):
# print(i['cate'][0])
pass
cates = []
for i in item_info.find():
cates.append(i['cate'][0])
cates_sets = list(set(cates))
# print(cates_sets)
post_times = []
for index in cates_sets:
post_times.append(cates.count(index))
# print(post_times)
def data_gen(type):
for cate, times in zip(cates_sets, post_times):
data = {
'name': cate,
'data':[times],
'type':type
}
yield data
series = [data for data in data_gen('column')]
charts.plot(series, show='inline', options=dict(title=dict(text='各分類發(fā)帖量對比匯總')))
總結(jié)
1. 思路
由于原始代碼的爬取邏輯問題滚粟,爬取到cates并不是大分類中的cates。
cates.png
所以只能根據(jù)item_info中的cates鹏漆,取出第一個元素(主分類)嫁盲,來大致看出分類發(fā)帖量情況。
2. set 沪蓬、count 進階用法
cates_sets = list(set(cates)) // 重復數(shù)組 變成 無重復數(shù)組
// 查看各cate在重復數(shù)組中的重復次數(shù)
for index in cates_sets:
print( cates.count(index) )
3. yield
先看一個簡單的例子:
def count(n):
print ("cunting" )
while n > 0:
# print ('before yield')
yield n #生成值:n
n -= 1
# print ('after yield' )
for x in count(5):
print(x)
這算是py語言中, 比較詭異的一種.
for in 中可以 直接取 count(5)中的值, 說明函數(shù)返回值是一個list, 否則無法取值.
其實可以先想想在oc中是如何實現(xiàn)的, 肯定是在定義count函數(shù)最后, return一個數(shù)組.
但是py中追求極簡的語法表達方式, 使用 yield 語法會生成一個迭代對象, 可以理解為就是存到了一個list中,
并且循環(huán)會接著往下進行.
// 本例中的使用
def data_gen(type):
for cate, times in zip(cates_sets, post_times):
data = {
'name': cate,
'data':[times],
'type':type
}
yield data
// 這里的意思就是彤钟,調(diào)用這個函數(shù)后,會return一個含有多個格式化好的data數(shù)組
// 所以下面才可以這樣調(diào)用:
series = [data for data in data_gen('column')]
4. 結(jié)果數(shù)據(jù)分析
- 數(shù)據(jù)分析表
分類 | 帖子數(shù)量 |
---|---|
QQ號碼 | 2878 |
筆記本電腦 | 1485 |
手表 | 1709 |
電腦包 | 955 |
家畜/家禽 | 1262 |
鋼琴 | 1184 |
虛擬物品 | 1099 |
農(nóng)用機械 | 1074 |
家具轉(zhuǎn)讓 | 1550 |
手機 | 1881 |
苗木 | 1644 |
有了大數(shù)據(jù)作支撐跷叉,二手賣家該賣什么就知道了吧~