Basic analysis: working
with JSON data
• Computing network centrality metrics can be slow, especially for large networks.
• JSON (JavaScript Object Notation) is a lightweight data interchange format which
can be used to serialize and deserialize Python objects (dictionaries and lists).
import json
# Utility function: saves data in JSON format
def dump_json(out_file_name, result):
with open(out_file_name, 'w') as out_file:
out_file.write(json.dumps(result, indent=4, separators=(',', ': ')))
# Utility function: loads JSON data into a Python object
def load_json(file_name):
with open(file_name) as f:
return json.loads(f.read())
path = 'betwenness_centrality.txt' # Example
dump_json(path, bet_cen)
saved_centrality = load_json(path) # Result is a Python dictionary
38
Writing your own code: BFS
• With Python and NetworkX it is easy to write any graph-based algorithm
from collections import deque
def breadth_first_search(g, source):
queue = deque([(None, source)])
enqueued = set([source])
while queue:
parent, n = queue.popleft()
Dostları ilə paylaş: