[英]Dictionary in Python not working correctly from csv file
I have a csv
file that contains wifi information about different companies in my area. 我有一个
csv
文件,其中包含有关我所在地区的不同公司的wifi信息。 The name of the telco that they get their wifi from is located in one column. 他们从中获取wifi的电信公司名称位于一栏中。 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.
我需要在python中创建一个字典,并以telco名称作为键,并将其在列中出现的次数作为值。
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. 我正在使用
.read().splitlines()
方法读取csv
,但是由于某些单元格包含逗号,因此实际上很难拆分数据。
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]
Use csv module instead so you will be able to declare comma as delimiter: 请改用csv模块,这样便可以将逗号声明为定界符:
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 然后,您可以遍历读者以获取逗号分隔的值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.