python - 编写一个字典,其中的值是不带括号的csv整数列表

该脚本读取包含错误消息的文件syslog.log,对其进行解析,构建字典,然后将字典写入文件user_statistics.csv。


我想写出key:list不带括号、引号或空格的整数。


#!/usr/bin/python3

import csv



per_user = {'noel': [2, 2], 'mcintosh': [2, 1], 'enim.non': [1, 1], 'oren': [0, 2], 'bpacheco': [0, 1], 'mdouglas': [0, 1], 'ac': [1, 0], 'blossom': [0, 1]}


with open('user_statistics.csv', 'w') as csvfile1:

        y = csv.writer(csvfile1)  

        y.writerow(['Username', 'INFO', 'ERROR'])

        y.writerows(per_user.items())

user_statistics.csv 中收到的输出


Username,INFO,ERROR

ac,"[1, 0]"

blossom,"[0, 1]"

bpacheco,"[0, 1]"

enim.non,"[1, 1]"

mcintosh,"[2, 1]"

mdouglas,"[0, 1]"

oren,"[0, 2]"

期望的输出是


Username,INFO,ERROR

ac,1,0

blossom,0,

bpacheco,0,1

enim.non,1,1

mcintosh,2,1

mdouglas,0,1

oren,0,2


拉丁的传说
浏览 78回答 2
2回答

慕莱坞森

你只需要做类似的事情:import csvper_user = {'noel': [2, 2], 'mcintosh': [2, 1], 'enim.non': [1, 1], 'oren': [0, 2], 'bpacheco': [0, 1], 'mdouglas': [0, 1], 'ac': [1, 0], 'blossom': [0, 1]}with open('user_statistics.csv', 'w') as csvfile1:    writer = csv.writer(csvfile1)      writer.writerow(['Username', 'INFO', 'ERROR'])    for name, (info, error) in per_user.items():        writer.writerow([name, info, error])

冉冉说

用 pandas 解决方案(而不是第二个with语句)。import pandas as pdkeys = per_user.keys()values = per_user.values()df_keys = pd.DataFrame(keys, columns=['Username'])df_values = pd.DataFrame(values, columns=['INFO', 'ERROR'])data = df_keys.join(df_values)data.to_csv("user_statistics.csv", index=False)输出:Username,INFO,ERRORac,1,0blossom,0,1bpacheco,0,1enim.non,1,1mcintosh,2,1mdouglas,0,1oren,0,2
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python