如何将这部分数据写入csv文件? [英] How do I write this piece of data to a csv file?

查看:97
本文介绍了如何将这部分数据写入csv文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据写入csv文件.数据格式混乱,无法更改.这就是数据字典的样子.我该如何在CSV文件中写入此数据?

I'm trying to write data to a csv file. The data is in a confusing format and I cannot change it. This is how the data dictionary looks like. How do i write this data in a csv file?

[{'box': [277, 90, 48, 63], 
  'confidence': 0.99, 
  'keypoints': {
    'left_eye': (291, 117), 
    'right_eye': (314, 114), 
    'nose': (303, 131), 
    'mouth_left': (296, 143), 
    'mouth_right': (313, 141)}
}]

我尝试使用下面的代码,但是,使用此代码仅将字段名称写入csv文件中,而不写入值.

I tried using the code below however, using this code only writes the field names in the csv file and not the values.

import csv 
with open('peak.csv', 'w') as csvFile:
    fields = ['box ', 'confidence', 'keypoints' ]
    writer = csv.DictWriter(csvFile, fieldnames=fields)
    writer.writeheader()
    writer.writerows(result)

print("writing completed")

csvFile.close()

这是我得到的结果. 结果

This is the result I'm getting. Results

推荐答案

快速事物的结合.您发布的函数在fields列表的'box'条目中有多余的空间,在python中,with关键字将自动为您关闭文件.无需明确地执行此操作.

Couple of quick things. The function you posted has an extra space in 'box' entry of the fields list, and in python the with keyword will automatically close a file for you. No need to do it explicitly.

我已经在运行Python 3.6的计算机上对此进行了测试.我在列表中包括一个重复项,因为我假设您的数据具有多个输出列表?如果没有的话,那应该没有什么不同.

I have tested this on my machine, running Python 3.6. I included a duplicate in the list because I assume your data has more than a single output list? If not it shouldn't make a difference.

您确定以下代码无效吗?

Are you sure the following code doesn't work?

import csv

data = [{'box': [277, 90, 48, 63],
         'confidence': 0.99,
         'keypoints': {
             'left_eye': (291, 117),
             'right_eye': (314, 114),
             'nose': (303, 131),
             'mouth_left': (296, 143),
             'mouth_right': (313, 141)}
         },
        {'box': [277, 90, 48, 63],
         'confidence': 0.99,
         'keypoints': {
             'left_eye': (291, 117),
             'right_eye': (314, 114),
             'nose': (303, 131),
             'mouth_left': (296, 143),
             'mouth_right': (313, 141)}
         }
        ]
# Write to csv
with open('data.csv', 'w') as f:
    fields = ['box', 'confidence', 'keypoints']
    w = csv.DictWriter(f, fieldnames=fields)
    w.writeheader()
    w.writerows(data)

# Append to existing csv
with open('data.csv', 'a') as f:
    fields = ['box', 'confidence', 'keypoints']
    w = csv.DictWriter(f, fieldnames=fields)
    w.writerows(data)

输出:

box,confidence,keypoints
"[277, 90, 48, 63]",0.99,"{'left_eye': (291, 117), 'right_eye': (314, 114), 'nose': (303, 131), 'mouth_left': (296, 143), 'mouth_right': (313, 141)}"
"[277, 90, 48, 63]",0.99,"{'left_eye': (291, 117), 'right_eye': (314, 114), 'nose': (303, 131), 'mouth_left': (296, 143), 'mouth_right': (313, 141)}"

LibreCalc中的输出是什么

如果要在它们自己的列中放置关键点的键:

If you want the keys of keypoints in their own columns:

import csv
data = [{'box': [277, 90, 48, 63],
         'confidence': 0.99,
         'keypoints': {
             'left_eye': (291, 117),
             'right_eye': (314, 114),
             'nose': (303, 131),
             'mouth_left': (296, 143),
             'mouth_right': (313, 141)}
         },
        {'box': [277, 90, 48, 63],
         'confidence': 0.99,
         'keypoints': {
             'left_eye': (291, 117),
             'right_eye': (314, 114),
             'nose': (303, 131),
             'mouth_left': (296, 143),
             'mouth_right': (313, 141)}
         }
        ]
with open('data2.csv', 'w') as f:
    # get a list of the keys in the values of 'keypoints' key
    kps = data[0].get('keypoints').keys()
    # make the list for the fieldnames, * just expands a list to its components
    fields = ['box', 'confidence', *kps]
    w = csv.DictWriter(f, fieldnames=fields)
    w.writeheader()
    out_dict = {}

    # Loop over however many data dictionaries are in the list data
    for data_dict in data:
        # Loop over keys and values in the dictionary 
        for k, v in data_dict.items():
            if k != 'keypoints':
                out_dict.update({k: v})
            elif k == 'keypoints':
                # Loop over the keys that correspond to 'keypoints' key
                for k2, v2 in data_dict['keypoints'].items():
                    out_dict.update({k2: v2})
        # Write the created out dictionary to the file
        w.writerow(out_dict)

# Appending to an already existing csv
with open('data2.csv', 'a') as f:
    kps = data[0].get('keypoints').keys()
    # make the list for the fieldnames, * just expands a list to its components
    fields = ['box', 'confidence', *kps]
    w = csv.DictWriter(f, fieldnames=fields)

    out_dict = {}
    # Loop over however many data dictionaries are in the list data
    for data_dict in data:
        # Loop over keys and values in the dictionary
        for k, v in data_dict.items():
            if k != 'keypoints':
                out_dict.update({k: v})
            elif k == 'keypoints':
                # Loop over the keys that correspond to 'keypoints' key
                for k2, v2 in data_dict['keypoints'].items():
                    out_dict.update({k2: v2})
        # Write the created out dictionary to the file
        w.writerow(out_dict)

具有以下输出:

box,confidence,left_eye,right_eye,nose,mouth_left,mouth_right
"[277, 90, 48, 63]",0.99,"(291, 117)","(314, 114)","(303, 131)","(296, 143)","(313, 141)"
"[277, 90, 48, 63]",0.99,"(291, 117)","(314, 114)","(303, 131)","(296, 143)","(313, 141)"

在LibreCalc中平展输出

第二个功能实际上与将json平展为提到的其他答案之一相同,只是没有依赖性.

This second function is effectively the same as flattening a json as one of the other answers mentioned, just without a dependency.

这篇关于如何将这部分数据写入csv文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆