如何将文本表转换为CSV文件

时间:2020-06-24 15:20:16

标签: python dataframe parsing

我有一个文本表text table,我想将它们保存到python中的csv文件中。我的代码附在下面,我的输出看起来像这样output table。该代码仅成功了一半,因为它错过了没有数字的条目。有人可以帮我吗?

def row(l):
    l = l.split()
    number_columns = 6
    if len(l) >= number_columns:
        data_row = [''] * number_columns
        first_column_done = False

        index = 0
        for w in l:
            if not first_column_done:
                data_row[0] = ' '.join([data_row[0], w])
                if '...' in w:
                    first_column_done = True
            else:
                index += 1
                data_row[index] = w

        return data_row


def take_table(table):
    owner = []
    Num_share = []
    middle = []
    middle_1 = []
    prior_offering = []
    after_offering = []

    for r in table:
        data_row = row(r)
        if data_row:
            col_1, col_2, col_3, col_4, col_5, col_6 = data_row
            owner.append(col_1)
            Num_share.append(col_2)
            middle.append(col_3)
            middle_1.append(col_4)
            prior_offering.append(col_5)
            after_offering.append(col_6)

    table_data = {'owner': owner, 'Num_share': Num_share, 'middle': middle, 'middle_1': middle_1,
                  'prior_offering': prior_offering, 'after_offering': after_offering}
    return table_data

dict_table = take_table(table)
a = pd.DataFrame.from_dict(dict_table)
a.to_csv('trail2.csv')

0 个答案:

没有答案