Python中的字典无法从csv-fi正常工作

2024-05-19 01:15:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个csv文件,其中包含我所在地区不同公司的wifi信息。他们获取wifi的电信公司的名称位于一列中。我需要用python创建一个字典,其中telco name作为键,它在列中出现的次数作为值。你知道吗

我正在使用.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]

Tags: orcsvinreadiflinenotkeys
1条回答
网友
1楼 · 发布于 2024-05-19 01:15:54

改用csv模块,这样您就可以将逗号声明为分隔符:

import csv

with open("/Users/marknovice/Downloads/Updated_Cafe.csv", "rb") as csvfile:
    reader = csv.reader(csvfile, delimiter=str(u','), quotechar=str(u'"'))

然后您可以在阅读器上迭代以获得逗号分隔的值

相关问题 更多 >

    热门问题