Graphics Reference
In-Depth Information
2. For each line in the link file, take the source node and the target node
and add them to a list of nodes, checking to make sure that nodes are
not duplicated.
3. Write out the node file.
CSV File and Lists
Pythonhasacomma-separatedvalue(CSV)readerlibrarywithfunctionality
to make it easy to parse .csv and tab-delimited ( .txt ) files. The following
code opens the .csv file and calls a function to add two nodes per each row:
import csv
# open the link file
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])
The first line imports the Python csv library. The next two lines open
the text file SciFiWriters.txt as read-only ( "r" ) and set the delimiter
to tab ( "\t" ) as opposed to the default, which is a comma. The file has
a header row ( subject influence ), which is skipped over using
next(datareader, None) .
The csv library turns each row of input into a list data structure. You can
access each field in the list using an index (referred to in Python as a slice ).
The index is an integer, starting at zero for the first item. For example,
consider a data row in the data file:
Stephen King Edgar Allan Poe
The first item is accessed using row[0] , which returns Stephen King ,
while row[1] returns Edgar Allan Poe ,andsoon.Youcanreferencethe
entire row simply using row .
Search WWH ::




Custom Search