Graphics Reference
In-Depth Information
Thekeyisusedtoretrievethenodewith
node = nodemap[name]
.Writing
each row requires passing a single object to the
formatter
. Because the
datamustbeinaspecificordertomatchthecolumnheaders,eachdataitem
is placed in order (for example,
node["nodeid"], node["count"]
, and
so on), and the overall set is placed into a list (denoted with square brackets,
[]
) and passed to the
formatter
.
The Python script and the sample data set are available in the Supplemental
Materials on this topic's companion website. The overall Python script looks
like this:
import csv
nodemap = {}
# define function to find or add a node; and adjust
its count
def addNode(name):
if name in nodemap:
node = nodemap[name]
node["count"] += 1
else:
node = {"nodeid": name, "count": 1}
nodemap[name] = node
return
with open ("SciFiWriters.txt", "r") as inputfile:
datareader = csv.reader(inputfile, delimiter="\t")
# skip the header row
next(datareader, None)
# process each row: add source node and target
node
for row in datareader:
addNode(row[0])
addNode(row[1])
#write out nodes
with open("nodes.txt", "w", newline="") as nodefile:
formatter = csv.writer(nodefile, delimiter="\t")
formatter.writerow(["Id","Count"])