0

Ok, so here's the deal.

I've got a CSV file in the following format (example):

Jon | Steve
Frank | Joe
Steve | Jon
Joe | Jon

I want to create a python program that reads in the CSV file and outputs a count of relationships, if that makes any sense. For example, for that example imput, the new .CSV file would be:

Jon | Steve | 2
Frank | Joe | 1
Joe | Jon | 1

Any ideas?

Thanks

2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by jice
0

You can use the csv module :
http://docs.python.org/library/csv.html

or, as your case is simple, do it yourself :

f=open('myfile.txt','r') # Opens the file read only
d={} # Dict to store result
for line in f:  # For each line of the file
    sline=line.rstrip('\n').split(" | ")  # split the line according to separators used in your file (here " | ")
    if len(sline)>1: # we don't want to process empty lines
        sline.sort() # to have the same order for all records (avoid double testine)
        key=tuple(sline) # Dictionary keys can't be lists
        try:
            d[key]+=1 # Add one
        except KeyError: # If the key doesn't exists yet, count is 1
            d[key]=1
print d
f.close()
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.