Skip to content

Instantly share code, notes, and snippets.

@drewconway
Created January 17, 2011 18:31
Show Gist options
  • Save drewconway/783214 to your computer and use it in GitHub Desktop.
Save drewconway/783214 to your computer and use it in GitHub Desktop.
A function, which given a list of Twitter users, creates NetworkX object of relationships.
def twitter_network(users, api, user_type="search", alt_type="friend"):
"""
Given a list of Twitter users, create NetworkX object of relationships.
args: users List of Twitter users as strings
user_types Type string for entries in 'users'
"""
twitter_network=nx.DiGraph()
# Iteratively create network with appropriate type data
users=list(users)
for u in users:
try:
user=api.GetUser(u)
if user.protected is False:
user_friends=api.GetFriends(u)
for j in user_friends:
friend_name=j.screen_name
twitter_network.add_nodes_from([u,friend_name], type=alt_type)
twitter_network.add_edge(u,friend_name)
except twitter.TwitterError:
print("Warning: user "+u+" was not found. Ignoring.")
users.remove(u)
# Reset node type for users
twitter_network.add_nodes_from(users, type=user_type)
return twitter_network, nx.weakly_connected_component_subgraphs(twitter_network)[0], nx.subgraph(twitter_network, users)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment