0

我是 python 新手,需要帮助。我正在尝试制作逗号分隔值的列表。我有这个数据。

EasternMountain 84,844 39,754 24,509 286 16,571 3,409 315 
EasternHill 346,373 166,917 86,493 1,573 66,123 23,924 1,343 
EasternTerai 799,526 576,181 206,807 2,715 6,636 1,973 5,214 
CentralMountain 122,034 103,137 13,047 8 2,819 2,462 561 

现在我怎么得到这样的东西;

"EasternMountain": 84844,
"EasternHill":346373,

等等??

到目前为止,我已经能够做到这一点:

 fileHandle = open("testData", "r")
 data = fileHandle.readlines()
 fileHandle.close()

 dataDict = {}

 for i in data:
    temp = i.split(" ")

    dataDict[temp[0]]=temp[1]
    with_comma='"'+temp[0]+'"'+':'+temp[1]+','
    print with_comma
4

2 回答 2

3

使用 csv 模块

import csv
with open('k.csv', 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=' ')
    my_dict = {}
    for row in reader:
        my_dict[row[0]] = [''.join(e.split(',')) for e in row[1:]]

print my_dict

k.csv 是一个文本文件,其中包含:

EasternMountain 84,844 39,754 24,509 286 16,571 3,409 315 
EasternHill 346,373 166,917 86,493 1,573 66,123 23,924 1,343 
EasternTerai 799,526 576,181 206,807 2,715 6,636 1,973 5,214 
CentralMountain 122,034 103,137 13,047 8 2,819 2,462 561 

输出:

{'EasternHill': ['346373', '166917', '86493', '1573', '66123', '23924', '1343', ''], 'EasternTerai': ['799526', '576181', '206807', '2715', '6636', '1973', '5214', ''], 'CentralMountain': ['122034', '103137', '13047', '8', '2819', '2462', '561', ''], 'EasternMountain': ['84844', '39754', '24509', '286', '16571', '3409', '315', '']}
于 2013-07-10T11:37:07.353 回答
0

尝试这个:

def parser(file_path):
    d = {}
    with open(file_path) as f:
        for line in f:
            if not line:
                continue
            parts = line.split()
            d[parts[0]] = [part.replace(',', '') for part in parts[1:]]
    return d

运行它:

result = parser("testData")
for key, value in result.items():
    print key, ':', value

结果:

EasternHill : ['346373', '166917', '86493', '1573', '66123', '23924', '1343']
EasternTerai : ['799526', '576181', '206807', '2715', '6636', '1973', '5214']
CentralMountain : ['122034', '103137', '13047', '8', '2819', '2462', '561']
EasternMountain : ['84844', '39754', '24509', '286', '16571', '3409', '315']
于 2013-07-10T11:38:11.043 回答