[英]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.