【发布时间】:2017-07-18 09:14:38
【问题描述】:
我有一个 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]
【问题讨论】:
-
JFYI,python 自带
csvmodule。 -
非常感谢,我开始研究它并一直在使用它。
标签: python python-2.7 csv dictionary