尝试从文本文件创建字典

时间:2012-10-31 03:49:38

标签: python dictionary list-comprehension

fieldict(filename)以DOT格式读取文件  返回带有DOT CMPLID的字典,转换为  整数,作为键,元组作为对应的值  为那把钥匙。元组的格式是:  (制造商,日期,崩溃,城市,州)

fieldict("DOT500.txt")[416]
  ('DAIMLERCHRYSLER  CORPORATION', datetime.date(1995, 1, 9), False, 'ARCADIA', 
到目前为止,我已经尝试了

from collections import defaultdict
import datetime

def fieldict(filename):
    with open(filename) as f:
        x=[line.split('\t')[0].strip() for line in f] #list of complaint numbers
        y= line.split('\t') #list of full complaints
        d={}
        for j in x:
            Y= True
            N= False
            d[j] = tuple(y[2],datetime.date(y[7]), y[6], y[12], y[13])   #dict with number of complaint as key and tuple with index as values
        return d

没有运气......我想我很接近..非常感谢你的帮助

编辑:每个投诉的格式都是这样的

'11\t958128\tDAIMLERCHRYSLER CORPORATION\tDODGE\tSHADOW\t1990\tY\t19941117\tN\t0\t0\tENGINE AND ENGINE COOLING:ENGINE\tWILMINGTON  \tDE\t1B3XT44KXLN\t19950103\t19950103\t\t1\tENGINE MOTOR MOUNTS FAILED, RESULTING IN ENGINE NOISE. *AK\tEVOQ\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tV\t\r\n'

没有字符标记的条目显示:

11  958128  DAIMLERCHRYSLER CORPORATION DODGE   SHADOW  1990    Y   19941117    N   0   0   ENGINE AND ENGINE COOLING:ENGINE    WILMINGTON      DE  1B3XT44KXLN 19950103    19950103        1   ENGINE MOTOR MOUNTS FAILED, RESULTING IN ENGINE NOISE.  *AK EVOQ    

3 个答案:

答案 0 :(得分:2)

注意:修剪换行符由读者完成。

实现此目的的一种简洁方法是使用dict(zip(headers,data_list))

假设您的样本数据类似于

joe\tSan Francisco\tapple
frank\tNew York City\torange
tim\tHawaii\tpineapple

您可以执行以下操作:

results = []
headers = ['person','place','fruit']

for line in open('datafile.txt').readlines():
    record = line.split('\t')
    results.append(dict(zip(headers,record)))

这将为每一行创建一个dict,并将其附加到'结果'的末尾。

看起来像:

[{'fruit': 'apple\n', 'person': 'joe', 'place': 'San Francisco'},
 {'fruit': 'orange\n', 'person': 'frank', 'place': 'New York City'},
 {'fruit': 'pineapple\n', 'person': 'tim', 'place': 'Hawaii'}]

答案 1 :(得分:2)

您希望与csv模块结交朋友,因为这看起来像标签格式化的csv文本。 csv.reader()有一个.next()方法,当你在for循环中抛出它时会调用它,所以你可以逐行浏览文件。

作为一般提示,请阅读PEP8,并使用可理解的变量名称。 使用python,如果它开始感觉很难,这是一个好的迹象,通常有更好的方法。

import csv
import datetime

def _build_datetime(line)
    year_idx = x
    month_idx = y
    day_idx = z
    indexes = (year_idx, month_idx, day_idx)

    result_datetime = None
    if all(line[idx] for idx in indexes): # check that expected values are populated
        int_values = [int(line[idx]) for idx in indexes]
        result_datetime = datetime.date(*int_values)
    return result_datetime

def format2dict(filename):
    complaints = {}
    with open(filename, "rb") as in_f:
        reader = csv.reader(in_f, delimiter='\t')
        complaint_id_idx = 0
        manufacturer_idx = 2
        crash_idx = x
        city_idx = 12
        state_idx = 13

        for line in reader:
            complaint_id = int(line[complaint_id_idx])
            data= (
                         line[manufacturer_idx], 
                         _build_datetime(line),
                         line[crash_idx],
                         line[city_idx],
                         line[state_idx],
                        )

            complaints[complaint_id] = data
    return complaints


if __name__ == "__main__":
    formatted_data = format2dict("DOT500.txt")

答案 2 :(得分:1)

你使用line.split('\ t')在正确的轨道上将文本拆分成碎片。尝试这样的东西来从分裂的部分构建元组。

import datetime

a = '11\t958128\tDAIMLERCHRYSLER CORPORATION\tDODGE\tSHADOW\t1990\tY\t19941117\tN\t0\t0\tENGINE AND ENGINE COOLING:ENGINE\tWILMINGTON  \tDE\t1B3XT44KXLN\t19950103\t19950103\t\t1\tENGINE MOTOR MOUNTS FAILED, RESULTING IN ENGINE NOISE. *AK\tEVOQ\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tV\t'

fields = a.split('\t')
recordNum = fields[0]
mfr = fields[2]
recDate = datetime.date(int(fields[5]),1,2)
make = fields[4]
DOTrecord = recordNum,mfr, recDate,make
print DOTrecord