gpt4 book ai didi

python - 试图从文本文件创建字典

转载 作者:行者123 更新时间:2023-11-28 22:01:19 25 4
gpt4 key购买 nike

fieldict(filename) 读取 DOT 格式的文件并 返回带有 DOT CMPLID 的字典,转换为 整数,作为键,一个元组作为对应的值 对于那把 key 。元组的格式是: (制造商、日期、事故、城市、州)

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    

最佳答案

看起来你想和 csv 交 friend 模块,因为这看起来像制表符格式的 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")

关于python - 试图从文本文件创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13151005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com