0

它需要一个包含 500 个投诉的文件,返回投诉的编号作为键,返回一个以汽车品牌、投诉日期、Crash True or False、City 和 State 为值的元组。

 ex)   mydict("Complaints.txt")[416]
      ('CHRYSLER', datetime.date(1995, 1, 9), False, 'ARCADIA', 'FL')

到目前为止,我有:

 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

y 是将整个投诉分解为一个列表,其中删除了 \t 字符。如果有人能指出我正确的方向,将不胜感激

4

2 回答 2

3

您也可以稍微依赖 csv 模块(未经测试):

import csv

def fieldict(filename):
    fullDict = {}
    with open(filename) as f:
        reader = csv.reader(f, delimiter='\t')
        for y in reader:
            fullDict[y[0].strip()] = (y[2],datetime.date(y[7]), y[6], y[12], y[13])
    return fullDict

if __name__ == "__main__":
    mydict = fieldict("Complaints.txt")
    print mydict[416]
于 2012-10-25T02:44:10.707 回答
0

如果我对您的理解正确,我认为这就是您要寻找的。

import datetime

def fieldict(filename):
    returnDict = {}
    with open(filename) as f:
        for line in f:
            lineList = line.split('\t')
            index = lineList[0].strip()
            complaint = tuple(lineList[2],datetime.date(lineList[7]), lineList[6], lineList[12], lineList[13])

            returnDict[index] = complaint

    return returnDict

if __name__ == "__main__":
    mydict = fieldict("Complaints.txt")
    print mydict[416]
于 2012-10-25T02:37:21.823 回答