【问题标题】:Twitter hashtags network with networkx带有 networkx 的 Twitter 主题标签网络
【发布时间】:2019-06-27 18:14:23
【问题描述】:

首先我要道歉,因为我是 Twitter 数据分析的新手。

我想创建一个用户标签网络,根据用户的推文标签连接用户。我已经将推文存储在 MongoDB 中,但我无法从扩展实体对象中提取所有主题标签,老实说,我有点迷失在如何做到这一点上,你能否认为这可能是实现它的最佳方法?

我尝试将主题标签存储在数据框中的新列中,但我只能检索一个,这不起作用,因为我需要考虑推文中的所有主题标签才能建立连接。

我有以下代码来检索第二个数据帧中的主题标签

def get_tweet_data(df2):
    df2["user_id"] = df1["user"].apply(lambda x: x["id"])
    df2["screen_name"] = df1["user"].apply(lambda x: x["screen_name"])
    df2["hashtags"] = df1["entities"].apply(lambda x: x["hashtags"][0]["text"] if x["hashtags"] else np.nan)
    return df2

结果给了我:

我在哪里寻找这样的东西:

但是我有另一个问题,我需要根据他们的标签连接每个推文用户,这样用户就可以与#Puertos 的用户、#Pemex 的用户和#abierto 的用户建立联系。我不知道该怎么做。

使用以下代码制作图表:

G = nx.from_pandas_edgelist(
df2,
source = "screen_name",
target = "hashtags",
create_using = nx.Graph())

再次道歉,我才刚刚开始。

【问题讨论】:

  • 您好,欢迎来到 Stack Overflow!您能否在帖子中添加一些示例数据和您编写的代码?
  • 您好,我刚刚补充了更多信息,谢谢您的回复。

标签: python-3.x twitter networkx


【解决方案1】:

让我们一步一步来。首先,您想从每条推文中提取主题标签。对于这项任务,我喜欢this question 的第二个答案。在您的上下文中,这意味着运行类似:

df['hashtags']=df['text'].map(lambda s: [i for i in s.split() if i.startswith("#") ])

这将添加一个列,其中每个条目都是一个主题标签列表。

第二步涉及更多。我将首先创建一个由用户和主题标签组成的双向网络。边缘将用户与他们使用的主题标签联系起来。然后,您可以使用 NetworkX 的二分投影函数创建一个用户网络,其边缘指示共享主题标签的使用。以下是它可能如何工作的草图:

user_to_hashtags_dict=dict(df[['user_id','hashtags']].values) #a more convenient data structure: a dictionary with users as keys and the list of hashtags they use as values.
    B=nx.Graph() #create an empty graph
    for user in user_to_hashtags: #loop over all the users
        for hashtag in user_to_hashtags[user]: #for each user loop over the hashtags they use
            B.add_edge(user,hashtag) #add the edge User<->hashtag
actual_users_with_hashtags = [x for x in list(set(df.user_id)) if x in B.nodes()] #create a list of users actually appearing in the network - perhaps some tweeting users never used a hashtag and we want to ignore them.
G = nx.bipartite.weighted_projected_graph(B,nodes =actual_users_with_hashtags) #project the bipartite network onto the the users.

G 应该是您感兴趣的网络,包括用户之间边缘的权重,计算他们共同使用的主题标签的数量。

【讨论】:

  • 非常感谢!现在我可以像我想要的那样获取列中的所有主题标签! :)) 现在我在您提供的第二个代码中遇到了一个错误,我知道问的太多了,因为您已经帮了我很多。 G = nx.bipartite.weighted_projected_graph(B,nodes =user_to_hashtags_dict.keys()) KeyError: 415173881
  • 嗨 - 我添加了一行并更改了投影代码。我认为问题在于您的数据中有 Twitter 用户从不使用主题标签。它们没有添加到二分用户标签网络中,因此不能考虑用于投影。希望这会有所帮助!
  • 你好 Johannes 又是我,我在添加属性时遇到了一些问题,我想知道你是否能启发我 =/
猜你喜欢
  • 2014-04-15
  • 1970-01-01
  • 2011-02-12
  • 1970-01-01
  • 2013-12-16
  • 2016-08-11
  • 2012-12-03
  • 2012-01-20
  • 1970-01-01
相关资源
最近更新 更多