从python中的txt文件读取表

2024-04-27 17:19:50 发布

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

我在导入txt报告中编写的表时遇到问题。表格格式如下:

"""
Ò         NDG  ANAGRAFICA             RAPPORTO        S.CONTABILE       FIDO BASE           STR.       FIDO PROP. F./SC.  INIZ.   GG.
Ò              STATUS               POSIZIONE
Ò           
Ò           
Ò   335647423  ERNESTORI MATTIO 03/045/23467890*             5,67            0,00           0,00            13,20  1/73 02/03/21    3
Ò             +RIENTRO SCAD/SCO
Ò           
Ò   567890432  PIAL MASSIMILI   23/345/12345678*           131,42-           0,00           0,00           124,34  1/34 06/03/21    1
"""

我使用的代码如下:

data = pd.read_csv('test.txt', sep = '\s{2,}|\.\s{1,}', engine='python', skipinitialspace=True)
print(data)

但我有两个问题:

1.列标题和内容转到带有空格的新行

例如:

ANAGRAFICA

STATUS


ERNESTORI MATTIO

+RIENTRO SCAD/SCO

2.在列之间,我没有特定的模式。例如,“Anagrafica”列下的空格用作名称分隔符

我如何用Python解决这个问题?有人知道解决办法吗


Tags: txtdata格式报告statusfido表格空格
1条回答
网友
1楼 · 发布于 2024-04-27 17:19:50

这是一个有趣的问题。似乎有两个观察结果需要处理:1)行由空行分隔;2) 列可以向左或向右对齐,但在行中设置索引。 使用这两个确定性,可以使用以下设置:1)按索引拆分行;2) 根据是否由空列表(行)分隔,对列表列表中的行进行分组;3) 为相同索引在组中加入字符串:

import pandas as pd
from itertools import groupby

data = """
Ò         NDG  ANAGRAFICA             RAPPORTO        S.CONTABILE       FIDO BASE           STR.       FIDO PROP. F./SC.  INIZ.   GG.
Ò              STATUS               POSIZIONE
Ò           
Ò           
Ò   335647423  ERNESTORI MATTIO 03/045/23467890*             5,67            0,00           0,00            13,20  1/73 02/03/21    3
Ò             +RIENTRO SCAD/SCO
Ò           
Ò   567890432  PIAL MASSIMILI   23/345/12345678*           131,42-           0,00           0,00           124,34  1/34 06/03/21    1
"""

#list of indices to split lines on
indices = [1,13,32,48,66,81,96,113,120,128,133]
#split lines by indices, generates a list of lists
text = [[s[i:j].strip() for i,j in zip(indices, indices[1:]+[None])] for s in data.splitlines()]
#group items in the list together 
text = [list(g) for k, g in groupby(text, key=lambda x: all('' == s for s in x)) if k == False]
#join elements in groups and strip trailing whitespaces
text = [[item.strip() for item in l] for l in [list(map(" ".join, zip(*i))) for i in text]]
df = pd.DataFrame(text[1:], columns=text[0])

结果:

^{tb1}$

相关问题 更多 >