開始使用免費開始

逐日找出最熱門的看板:II

上一題做得很棒——你已經寫出能建立時間序列圖清單的程式碼。接下來要把那題完成:也就是要找出每天有多少個看板拿到最高的熱門度分數!

這裡你會用到「字典生成式」來過濾字典。它和用來過濾串列的串列生成式很像,但語法長這樣:{key: val for key, val in dict.items() if ...}。記得這個寫法喔!

本練習屬於課程

Python 網路分析進階

檢視課程

練習說明

  • 使用 nx.bipartite.degree_centrality() 取得度中心性,參數為 G_subforum_nodes
  • 過濾字典,讓結果只保留看板的度中心性。輸出表達式中的 key: val 應為 n, dc。對 dc.items() 進行迭代,並檢查 n 是否在 forum_nodes 中。
  • 找出最熱門的看板(們):其度中心性需為最高值(max(forum_dcs.values())),而且 DC 值不為 0。
  • 將最高的 dc 值加入 highest_dcs
  • 繪製圖表!
    • 第一張圖請使用串列生成式,對 most_popular_forums(一個由多個清單組成的清單)以 forums 為迭代變數做迭代。輸出表達式應為最熱門看板的「數量」,用 len() 計算。
    • 第二張圖使用 highest_dcs,搭配 plt.plot() 視覺化最高的度中心性分數。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Import necessary modules
from datetime import timedelta
import networkx as nx
import matplotlib.pyplot as plt

most_popular_forums = []
highest_dcs = []
curr_day = dayone 
td = timedelta(days=1)  

while curr_day < lastday:  
    if curr_day.day == 1:  
        print(curr_day)  
    G_sub = nx.Graph()
    G_sub.add_nodes_from(G.nodes(data=True))   
    G_sub.add_edges_from([(u, v, d) for u, v, d in G.edges(data=True) if d['date'] >= curr_day and d['date'] < curr_day + td])
    
    # Get the degree centrality 
    dc = ____
    # Filter the dictionary such that there's only forum degree centralities
    forum_dcs = {____:____ for ____, ____ in ____ if n in ____}
    # Identify the most popular forum(s) 
    most_popular_forum = [n for n, dc in ____ if dc == ____(____) and dc != 0] 
    most_popular_forums.append(most_popular_forum) 
    # Store the highest dc values in highest_dcs
    highest_dcs.append(max(____))
    
    curr_day += td  
    
plt.figure(1) 
plt.plot([len(____) for ____ in ____], color='blue', label='Forums')
plt.ylabel('Number of Most Popular Forums')
plt.show()

plt.figure(2)
plt.plot(____, color='orange', label='DC Score')
plt.ylabel('Top Degree Centrality Score')
plt.show()
編輯並執行程式碼