开始使用免费开始使用

逐日找出最热门的论坛: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_dcsplt.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()
编辑并运行代码