将数据字符串转换为CSV格式

时间:2019-01-22 01:01:54

标签: python

我正在从一个称为aa的大字符串中组织一些数据,并且它是conatin:

$print(aa)

"birthDate":"2010-01-21","tall":151,"weight":55.5,"showSize":41
,
"birthDate":"2011-05-21","tall":155,"weight":44.2,"showSize":42
,
"birthDate":"2012-11-27","tall":145,"weight":49.3,"showSize":43
,

...然后继续

与上述完全一样,我想将其放在csv中: 删除birthDate,tall,weight和showSize,仅保留数据如下:

2010-01-21 , 151 , 55.5 , 41  "\n "
2011-05-21 , 155 , 44.2 , 42  "\n "
2012-11-27 , 145 , 49.3 , 43  "\n "

2 个答案:

答案 0 :(得分:0)

我相信您可以使用

aa = aa.replace('"birthDate:"', "")

以此类推。


答案 1 :(得分:0)

尝试一下:

aa = "'birthDate':'2010-01-21','tall':151,'weight':55.5,'showSize':41\n,\n'birthDate':'2011-05-21','tall':155,weight':44.2,'showSize':42\n,\n'birthDate':'2012-11-27','tall':145,'weight':49.3,'showSize':43\n,\n"
print("ORIGINAL>>>")
print(aa)

# Cleanup the input to change the separators.
bb = aa.replace("\n,", "")
print("MODIFIED>>>")
print(bb)

# Split the "big string" into a list of lines then iterate over them.
for line in bb.split():

    # Stop on the last line
    if len(line) == 0:
        break

    # For each line, split it into "key":"value" items.
    # Then split each item again to get the "value" part.
    # Store each "value" in a list.
    csv_cols = list()
    for item in line.split(","):
        csv_cols.append(item.split(":")[1])

    # Combine the list elements into a string.
    csv_row = ",".join(csv_cols)
    print(csv_row)

输出:

ORIGINAL>>>
'birthDate':'2010-01-21','tall':151,'weight':55.5,'showSize':41
,
'birthDate':'2011-05-21','tall':155,weight':44.2,'showSize':42
,
'birthDate':'2012-11-27','tall':145,'weight':49.3,'showSize':43
,

MODIFIED>>>
'birthDate':'2010-01-21','tall':151,'weight':55.5,'showSize':41
'birthDate':'2011-05-21','tall':155,weight':44.2,'showSize':42
'birthDate':'2012-11-27','tall':145,'weight':49.3,'showSize':43

'2010-01-21',151,55.5,41
'2011-05-21',155,44.2,42
'2012-11-27',145,49.3,43