首页 > 解决方案 > 在 Python 中读取非结构化文本文件以使其结构化

问题描述

文件我有这个附加的文本文件,其中包含之前带有一些信息行的非结构化数据。我如何结构化这些数据(以结构化方式提取信息)。所以最后我有几列(在本例中为 5)并在其中包含相应的信息。第 50 帧包含 10 个值,第 51 帧包含 10 个值,依此类推,并分别获取前 4 行值。我尝试了以下代码。但这不是我得到的最好的列表/数组。谢谢

frame =[]
frame1 =[]

flag = -1
counter = -1
counter_val = 0
f = open(filepath, "r")
for line in f:
    element = line.split(' ')
    if(len(element) == 4):
        if(element[1] == "Frame_Number") :
            # print(element[1])
            if(flag == 0):
                # print(len(frame1))
                frame.append(frame1)
            flag = 0
            counter = counter + 1
            counter_val = 0
            frame1 =[]
        continue
    if(flag == 0):   
        frame1.append(line)
        counter_val = counter_val + 1

print(frame[1])

标签: pythonpython-3.x

解决方案


这是一个熊猫解决方案,

import pandas as pd

# Read in the data as a Pandas Series
df = pd.read_csv('testsd.txt', sep = '\n', header = None, squeeze = True) 

# Get the names of the eventual column names ('# Frame_Number 50', ...)
colNames = df.loc[df.str.startswith('# Frame_Number')]

# Store the first few lines of metadata in another frame and drop them from the original dataframe
meta_df = df[: colNames.index.to_list()[0]]]
df.drop(range(colNames.index.to_list()[0]), inplace = True)

# Drop the eventual column names
df.drop(colNames.index.to_list(), inplace = True)

原始数据框中剩下的应该只是数据。现在重塑数据框。请注意,这仅在每列具有相同数量的条目时才有效。

df = pd.DataFrame(df.values.reshape(len(colNames), int(len(df) / len(colNames))).T, columns = colNames)

reshape 函数将所需的行数和列数作为参数。它水平重塑,所以我们将转置结果。最后,如果您愿意,可以添加我们保存为数据框列的元数据,尽管您确实应该将其保存为其他地方的文件。

df['meta'] = meta_df

将数据框写入文件:

df.to_csv('testsd.csv')

输出:

在此处输入图像描述


推荐阅读