2

fieldict(filename) 读取 DOT 格式的文件并返回一个字典,其中 DOT CMPLID 转换为整数,作为键,元组作为该键的对应值。元组的格式为:(manufacturer, date, crash, city, state)

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    
4

3 回答 3

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)))

这将为每一行制作一个字典并将其附加到“结果”的末尾。

看起来像:

[{'fruit': 'apple\n', 'person': 'joe', 'place': 'San Francisco'},
 {'fruit': 'orange\n', 'person': 'frank', 'place': 'New York City'},
 {'fruit': 'pineapple\n', 'person': 'tim', 'place': 'Hawaii'}]
于 2012-10-31T05:14:32.503 回答
2

看起来您想与csv模块交朋友,因为这看起来像制表符格式的 csv 文本。csv.reader()有一个方法,当您将其放入 for 循环时会调用该.next()方法,因此您可以逐行浏览文件。

作为一般提示,请阅读 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")
于 2012-10-31T08:56:38.403 回答
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
于 2012-10-31T06:37:10.210 回答