如何将字符串转换为结构化表格表?

时间:2019-05-12 02:13:29

标签: python

我有一个像这样的字符串:

function discordReady(client) {
    return new Promise((resolve, reject) => {

        client.once('ready', async () => {
            reject(new Error('Omg'));

            // resolve..
        }); 
    })
}


async function start() {
  try {
    await Promise.all([
        discordReady(client),
        client.login(process.env.DISCORD_BOT_TOKEN),
    ]);
  } catch (err) {
    console.error('Caught the promise rejections');
  }
}

,我需要将其转换为表格。我不知道。

我正在尝试使用split或find函数,但距离anwser远。

请帮助!

2 个答案:

答案 0 :(得分:1)

您的字符串是有效的JSON片段。假设s是您的字符串,并且用“结构化表格表”表示Pandas DataDrame:

import pandas as pd
df = pd.read_json(s)
#    close       date     id
#0  908.35 2009-05-12  SP500
#1  883.92 2009-05-13  SP500
#2  893.07 2009-05-14  SP500
#3  882.88 2009-05-15  SP500
#4  909.71 2009-05-18  SP500

答案 1 :(得分:0)

如果要坚持使用标准库,可以使用json和csv模块。

import json
import csv

data = json.loads('''[{"id":"SP500","date":"2009-05-12","close":"908.3500"},
  {"id":"SP500","date":"2009-05-13","close":"883.9200"},
  {"id":"SP500","date":"2009-05-14","close":"893.0700"},
  {"id":"SP500","date":"2009-05-15","close":"882.8800"},
  {"id":"SP500","date":"2009-05-18","close":"909.7100"}]''')

with open('out.csv', 'w', newline='', encoding='utf8') as fp:
    writer = csv.DictWriter(fp, ('id', 'date', 'close'))
    for line in data:
        writer.writerow(line)