【问题标题】:Dictionary in Python not working correctly from csv filePython中的字典无法从csv文件正常工作
【发布时间】: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 自带csv module
  • 非常感谢,我开始研究它并一直在使用它。

标签: python python-2.7 csv dictionary


【解决方案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'"'))

然后您可以遍历您的阅读器以获取逗号分隔值

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 2020-09-20
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    相关资源
    最近更新 更多