这里有点像 Python 菜鸟。我有来自 Matthew Russell 的书“21 Recipes for Mining Twitter”和“Mining the Social Web”的 Python 代码,我想将它们用于一个项目,以从 Twitter API 收集各种数据请在此处查看他的 github 页面:https://github.com/ptwobrussell
我无法弄清楚的一件事是如何根据用户与其关注者/ friend 之间的关系生成网络矩阵/图表。因此,例如,这是他在 Twitter 上收集用户 friend 的 Python 代码(也在此处:https://github.com/ptwobrussell/Recipes-for-Mining-Twitter/blob/master/recipe__get_friends_followers.py):
# -*- coding: utf-8 -*-
import sys
import twitter
from recipe__make_twitter_request import make_twitter_request
import functools
SCREEN_NAME = sys.argv[1]
MAX_IDS = int(sys.argv[2])
if __name__ == '__main__':
# Not authenticating lowers your rate limit to 150 requests per hr.
# Authenticate to get 350 requests per hour.
t = twitter.Twitter(domain='api.twitter.com', api_version='1')
# You could call make_twitter_request(t, t.friends.ids, *args, **kw) or
# use functools to "partially bind" a new callable with these parameters
get_friends_ids = functools.partial(make_twitter_request, t, t.friends.ids)
# Ditto if you want to do the same thing to get followers...
# getFollowerIds = functools.partial(make_twitter_request, t, t.followers.ids)
cursor = -1
ids = []
while cursor != 0:
# Use make_twitter_request via the partially bound callable...
response = get_friends_ids(screen_name=SCREEN_NAME, cursor=cursor)
ids += response['ids']
cursor = response['next_cursor']
print >> sys.stderr, 'Fetched %i total ids for %s' % (len(ids), SCREEN_NAME)
# Consider storing the ids to disk during each iteration to provide an
# an additional layer of protection from exceptional circumstances
if len(ids) >= MAX_IDS:
break
# Do something useful with the ids like store them to disk...
print ids
所以我成功地以给定用户作为命令行参数的主要用户运行了这段代码。但是我如何真正将这些数据放入一个矩阵中,然后我可以分析,运行公式(如中心性)等等......?到目前为止,我认为我可能需要使用可能包括 NetworkX、Redis 和 Matplotlib 的软件包组合,但实际生成此矩阵的步骤让我望而却步。
最佳答案
您可以将数据存储在数据库或文件中。最好根据您将用于分析数据的软件支持什么来选择。
这是一个 .gdf
格式的文件示例,可让您存储节点和边数据:
nodedef> id VARCHAR, label VARCHAR, followerCount VARCHAR
1623,jchris,5610
13348,Scobleizer,319673
21213,tlg,1141
...
edgedef> user VARCHAR,friend VARCHAR
1623,13348
1623,621713
...
您在示例中引用的代码完成了提取边缘的部分,您还需要另一个提取步骤来提取节点。
关于matplotlib - 如何根据从 Twitter API 收集的数据生成网络矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16311339/