[英]Dictionary in Python not working correctly from csv file
我有一个csv
文件,其中包含有关我所在地区的不同公司的wifi信息。 他们从中获取wifi的电信公司名称位于一栏中。 我需要在python中创建一个字典,并以telco名称作为键,并将其在列中出现的次数作为值。
我正在使用.read().splitlines()
方法读取csv
,但是由于某些单元格包含逗号,因此实际上很难拆分数据。
码:
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)
结果:
['MyRepublic', 'StarHub', 'ViewQwest', 'M1', 'SingTel']
[1, 1, 1, 1, 1]
请改用csv模块,这样便可以将逗号声明为定界符:
import csv
with open("/Users/marknovice/Downloads/Updated_Cafe.csv", "rb") as csvfile:
reader = csv.reader(csvfile, delimiter=str(u','), quotechar=str(u'"'))
然后,您可以遍历读者以获取逗号分隔的值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.