【问题标题】:Reading data from csv file put into dictionary python从csv文件中读取数据放入字典python
【发布时间】:2016-01-16 02:59:19
【问题描述】:

块引用

帮助我阅读我的 csv 文件。我有一个 csv 文件 test8.csv,我想从该文件中读取数据并放入 dict,从 csv 文件:第一行是我将创建的 valuedict 的矩阵大小,第二行是 @ dict 的 987654325@ 和下一个是键值的 matrix

文件 csv:

1,5 
OFFENSE INVOLVING CHILDREN 
95   
96
35
80
100
2,2
BATTERY,THEFT
173,209   
173,224

输出期望:

dict={['OFFENSE INVOLVING CHILDREN']: 
      [(95,), (96,), (35,), (80,), (100,)], 
      ['BATTERY', 'THEFT']:[(173, 209), (173, 224)]}

这是我的一段代码,我不知道继续:

_dir = r'D:\s2\semester 3\tesis\phyton\hasil'
with open(os.path.join(_dir, 'test8.csv'), 'rb') as csv_file:
dataReader= csv.reader(csv_file, delimiter=' ', quotechar='|')

【问题讨论】:

  • 你不能有一个列表作为字典键,否则我在这里遗漏了一些东西。

标签: python python-2.7 csv dictionary


【解决方案1】:

这不是 csv 文件,csv 模块无法帮助您。在 csv 文件中,每一行都有相同数量的列字段,由已知字符(例如逗号)分隔。您需要为此数据编写自己的解析器。

此脚本将构建字典(除了它使用元组作为键,因为列表不起作用......)

# todo: write a testfile so the example works
open("testfile.txt", "w"). write("""1,5 # matriks size
OFFENSE INVOLVING CHILDREN # key for dictionary
95  # list of value 
96
35
80
100
2,2
BATTERY,THEFT
173,209   # list of tuple value
173,224""")

def strip_comment(line):
    return line.split('#', 1)[0].rstrip()

mydict = {}

with open("testfile.txt") as testfile:
    for line in testfile:
        # first line is the next record "matrix size"
        columns, rows = (int(x) for x in strip_comment(line).split(','))
        # next line is the header for this record
        key = tuple(strip_comment(next(testfile)).split(','))
        # the next lines are the rows for this record
        vals = [tuple(int(x) for x in   strip_comment(next(testfile)).split(','))
            for _ in range(rows)]
        mydict[key] = vals

print(mydict)

【讨论】:

  • 实际上这种情况与我的问题相反before
  • 抱歉...comment 不是 csv 文件的一部分。我写它只是为了解释我的 csv 示例。顺便说一句,用你的方式......如何从文件中读取数据。 testfile 的类型是什么? testfile 的输入类型是什么。就我而言,我只有 csv 文件。 :)
  • StringIO 只是一个看起来像文件的对象,实际上并没有写入文件。我更新了示例以删除 StringIO,但写入测试文件并从磁盘读取它。
  • 谢谢 :) 我会用你的解决方案
【解决方案2】:

CSV 文件是comma-separated values 文件的缩写。只需将您现在拥有的内容视为文本文件即可。

可以先将文件读入内存:

with open('test8.csv','r') as f:
    lines = f.readlines()

那么,既然文件的结构是已知的,那么就可以一一处理了。

def remove_line_comment(line,comment_char='#'):
    i = 0
    for c in line:
        if c != comment_char:
            i+=1
        else:
            break
    return line[:i]

output = dict() 

for line_number,line in enumerate(lines):
    line = remove_line_comment(line)
    line = line.strip()    # remove empty space on both sides
    line = line.split(',') # split the line with comma as the separator 

    # as indicated, I assume the first line in the file is always 
    # the indicative of the size of key and the size of value of the first diction item 
    if line_number == 0: 
        key_size, value_size = int(line[0]), int(line[1]) 
        line_number_counter = line_number 

    elif line_number == line_number_counter+1:
        # dictionary key cannot be unhashable object 
        key = line[0] if key_size == 1 else tuple(line) 
        value = []

    elif line_number >= line_number_counter+2 and line_number < line_number_counter+1+value_size: 
        value.extend[line]

    elif line_number == line_number_counter+1+value_size:
        value.extend(line)
        output[key] = value

    else:
        key_size, value_size = int(line[0]), int(line[1]) 
        line_number_counter = line_number 

这样就可以了。

【讨论】:

    猜你喜欢
    • 2023-01-08
    • 2018-03-19
    • 2021-08-20
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 2019-05-17
    相关资源
    最近更新 更多