繁体   English   中英

python csv字典格式调整

[英]python csv dictionary format adjust

import os
from datetime import datetime, date
def convert_file(file_path):
    with open(file_path) as file:
        next(file) 
        weather={}
        for line in file:
            line = line.rstrip("\n") 
            x=line.split(",")
            a=x[3]
            b=[x[-2],x[-1],x[4]]
            weather[a]=b
        print(weather)
        file.close()

file_path=os.getcwd()+"/weatherdata.csv"
convert_file(file_path)

{'"2010-07-03"': ['"68"', '"52"', '"0.00"'], '"1969-08-23"': ['"81"', '"54"', '"0.00"'], '"1983-07-10"': ['"69"', '"54"', '"0.00"'], '"1983-09-17"': ['"61"', '"49"', '"0.00"'], '"1964-04-22"': ['"50"', '"35"', '"0.33"']

如何使我的输出看起来像下面的示例输出?: 输出字典(天气):

{datetime.date(2017, 12, 10): [49, 34, 0.0],
 datetime.date(2017, 12, 11): [49, 29, 0.0],
 datetime.date(2017, 12, 12): [46, 32, 0.0],

考虑使用csv库解析 CSV 文件——现实世界的 CSV 可能非常复杂。 https://docs.python.org/3/library/csv.html

如果您要沿着手动路径走下去,请考虑通过line.strip('"')运行每一行以删除尾随/前导引号并使用line.split('","')或类似方法进行拆分以不包含引号在中心,假设您的 CSV 格式很好(如果没有,请使用库)。

您可以使用int(x)float(x)将字符串转换为数字:像b2 = [int(b[0]), int(b[1]), float(b[2])应该有帮助。

您可以使用datetime.strptime(date_string, format)将日期文本转换为日期时间对象——有关更多文档,请参阅https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior ,但您我认为需要%Y-%m-%d作为格式字符串。

最好使用 CSV 模块来处理 csv 文件。 但这应该会有所帮助...

import os
import ast
from datetime import datetime


def convert_file(file_path):
    with open(file_path) as file:
        next(file) 
        weather={}
        for line in file:
            line = line.rstrip("\n") 
            x=line.split(",")
            a=x[3]
            b=[x[-2],x[-1],x[4]]
            weather[datetime.strptime(a, '"%Y-%m-%d"')]= [ast.literal_eval(i.replace('"', "")) for i in b]
        print(weather)
        file.close()

file_path=os.getcwd()+"/weatherdata.csv"
convert_file(file_path)

您可以使用带有datetime.strptimeintfloat的列表datetime.strptime float 您可以通过字符串切片删除字符串中的双引号。

from datetime import datetime

d = {'"2010-07-03"': ['"68"', '"52"', '"0.00"'],
     '"1969-08-23"': ['"81"', '"54"', '"0.00"'],
     '"1983-07-10"': ['"69"', '"54"', '"0.00"'],
     '"1983-09-17"': ['"61"', '"49"', '"0.00"'],
     '"1964-04-22"': ['"50"', '"35"', '"0.33"']}

res = {datetime.strptime(k[1:-1], '%Y-%m-%d'): \
       [int(v[0][1:-1]), int(v[1][1:-1]), float(v[2][1:-1])] \
       for k, v in d.items()}

结果

print(res)

{datetime.datetime(1964, 4, 22, 0, 0): [50, 35, 0.33],
 datetime.datetime(1969, 8, 23, 0, 0): [81, 54, 0.0],
 datetime.datetime(1983, 7, 10, 0, 0): [69, 54, 0.0],
 datetime.datetime(1983, 9, 17, 0, 0): [61, 49, 0.0],
 datetime.datetime(2010, 7, 3, 0, 0): [68, 52, 0.0]}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM