Python将文本文件中的json数据添加到csv-fi的单个字段中

2024-06-16 10:15:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,其中包含逗号分隔的数据,还有json数据,所以我试图从中生成一个csv文件,但是json数据被拆分成不同的列,而不是在同一列下。那样的话,我需要帮助。
样本数据:

1,'22',2068,'zxzx@gmail.com','SCHEDULED',1,0,'2017-11-30 18:16:23',NULL,NULL,'{\"endpoint_AudioE2ELatency\":0.0,\"endpoint_VideoE2ELatency\":0.0,\"inboundrtp_inboundJitter\":0.004044444300234318,\"inboundrtp_bytesReceived\":28223,\"inboundrtp_packetsLost\":0,\"inboundrtp_remb\":0}',NULL,NULL,NULL,'{\"inboundrtp_inboundJitter\":0.0017291667172685266,\"inboundrtp_bytesReceived\":46411,\"inboundrtp_packetsLost\":0,\"inboundrtp_remb\":0,\"endpoint_AudioE2ELatency\":0.0,\"endpoint_VideoE2ELatency\":0.0,\"outboundrtp_roundTripTime\":0.317474365234375,\"outboundrtp_targetBitrate\":64265.0,\"outboundrtp_bytesSent\":87360,\"outboundrtp_packetsSent\":546,\"outboundrtp_packetsLost\":1,\"outboundrtp_remb\":0}',1

因此,突出显示的数据需要位于csv文件的同一字段中。
这是我目前的代码:

rg= re.compile('\{(?:{[^{}]*}|[^{}])*}')
def analyze_log(f):
stats = OrderedDict()
for line in f:
    if (rg.search(line)):
        stats = re.findall('\{(?:{[^{}]*}|[^{}])*}',line)
    else:
        stats = line
    return stats


def write_stats(stats, f):
   out = csv.writer(f)
   out.writerow(stats)

def main(input_filename, output_filename):
    with open(input_filename) as input_file:
        stats = analyze_log(input_file)
    with open(output_filename, 'w') as output_file:
        write_stats(stats, output_file)

if __name__ == '__main__':
    main(r'input.txt',
         r'Output.csv')

在analyze_log()中,我得到了同一个字段中的json部分,但缺少了其他数据。 提前谢谢。你知道吗


Tags: csv数据jsoninputoutputstatslinefilename
1条回答
网友
1楼 · 发布于 2024-06-16 10:15:23

据我所知,您的writer中的csv设置不正确。你知道吗

在write_stats方法中,将out赋值更改为以下内容,并查看是否获得更好的输出(您希望您的quotechar是单引号,因为您的json中有双引号):

out = csv.writer(f, quotechar="'")

至于为什么只在输出中获取json数据,这是因为这就是您在analyze\u log方法的regex中搜索的内容(它只返回json数据)。使用csv python模块来解析文件可能比使用自定义regex更容易。你知道吗

编辑:添加一些代码

如果JSON数据不是总是在每一行的同一列中,那么使用regex的方法最好。不过,如果JSON数据总是在同一列中,则可以使用相应的列表索引。我只提取了数据样本中的JSON,而不使用regex,使用以下代码:

import csv
with open('input.txt') as csvfile:
    reader = csv.reader(csvfile, delimiter=',', quotechar="'")
    for row in reader:
        print row[10], row[14]

相关问题 更多 >