結(jié)果

結(jié)果統(tǒng)計(jì)1.png

結(jié)果統(tǒng)計(jì)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ā)帖量對(duì)比匯總')))
總結(jié)
1. 思路
由于原始代碼的爬取邏輯問(wèn)題,爬取到cates并不是大分類中的cates。

cates.png
所以只能根據(jù)item_info中的cates,取出第一個(gè)元素(主分類),來(lái)大致看出分類發(fā)帖量情況。
2. set 、count 進(jìn)階用法
cates_sets = list(set(cates)) // 重復(fù)數(shù)組 變成 無(wú)重復(fù)數(shù)組
// 查看各cate在重復(fù)數(shù)組中的重復(fù)次數(shù)
for index in cates_sets:
print( cates.count(index) )
3. yield
先看一個(gè)簡(jiǎn)單的例子:
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語(yǔ)言中, 比較詭異的一種.
for in 中可以 直接取 count(5)中的值, 說(shuō)明函數(shù)返回值是一個(gè)list, 否則無(wú)法取值.
其實(shí)可以先想想在oc中是如何實(shí)現(xiàn)的, 肯定是在定義count函數(shù)最后, return一個(gè)數(shù)組.
但是py中追求極簡(jiǎn)的語(yǔ)法表達(dá)方式, 使用 yield 語(yǔ)法會(huì)生成一個(gè)迭代對(duì)象, 可以理解為就是存到了一個(gè)list中,
并且循環(huán)會(huì)接著往下進(jì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)用這個(gè)函數(shù)后,會(huì)return一個(gè)含有多個(gè)格式化好的data數(shù)組
// 所以下面才可以這樣調(diào)用:
series = [data for data in data_gen('column')]
4. 結(jié)果數(shù)據(jù)分析
- 數(shù)據(jù)分析表
| 分類 | 帖子數(shù)量 |
|---|---|
| QQ號(hào)碼 | 2878 |
| 筆記本電腦 | 1485 |
| 手表 | 1709 |
| 電腦包 | 955 |
| 家畜/家禽 | 1262 |
| 鋼琴 | 1184 |
| 虛擬物品 | 1099 |
| 農(nóng)用機(jī)械 | 1074 |
| 家具轉(zhuǎn)讓 | 1550 |
| 手機(jī) | 1881 |
| 苗木 | 1644 |
有了大數(shù)據(jù)作支撐,二手賣(mài)家該賣(mài)什么就知道了吧~