Reputation: 151
I have a csv
file that contains wifi information about different companies in my area. The name of the telco that they get their wifi from is located in one column. I need to create a dictionary in python with the telco name as the key and the number of occurrences that it occurs in the column as the value.
I am using the .read().splitlines()
method to read in the csv
, but I'm having a lot of trouble actually breaking up the data because some of the cells contain commas.
Code:
def printer(csvreadsplit): #prints each line of a csv that has been read and split
for line in csvreadsplit:
print line
file_new = open("/Users/marknovice/Downloads/Updated_Cafe.csv", "r")
lines1 = file_new.read().splitlines()
printer(lines1)
writer1 = open("Cafe_Data.csv", "w+")
def telcoappeareances(filecsv):
telconumber = {}
for line in filecsv:
if "Singtel" or "SingTel" in line:
if "Singtel" or "SingTel" not in telconumber.keys():
telconumber["SingTel"] = 1
else:
telconumber["SingTel"] += 1
if "Starhub" or "StarHub" in line:
if "Starhub" or "StarHub" not in telconumber.keys():
telconumber["StarHub"] = 1
else:
telconumber["StarHub"] += 1
if "Viewqwest" or "ViewQwest" in line:
if "Viewqwest" or "ViewQwest" not in telconumber.keys():
telconumber["ViewQwest"] = 1
else:
telconumber["ViewQwest"] += 1
if "M1" in line:
if ["M1"] not in telconumber.keys():
telconumber["M1"] = 1
else:
telconumber["M1"] += 1
if "MyRepublic" or "Myrepublic" in line:
if "MyRepublic" or "Myrepublic" not in telconumber.keys():
telconumber["MyRepublic"] = 1
else:
telconumber["MyRepublic"] += 1
print telconumber.keys()
print telconumber.values()
telcoappeareances(lines1)
Results:
['MyRepublic', 'StarHub', 'ViewQwest', 'M1', 'SingTel']
[1, 1, 1, 1, 1]
Upvotes: 0
Views: 132
Reputation: 603
Use csv module instead so you will be able to declare comma as delimiter:
import csv
with open("/Users/marknovice/Downloads/Updated_Cafe.csv", "rb") as csvfile:
reader = csv.reader(csvfile, delimiter=str(u','), quotechar=str(u'"'))
Then you can iterate over your reader to get your comma separated values
Upvotes: 1