将包含多个分隔符的文本文件转换为 CSV

问题描述

一个文本文件看起来像这样。我想将其转换为 CSV 文件

enter image description here

Water level.txt

使用 Pandas 时:

df = pd.read_fwf(f)

看起来像:

enter image description here

似乎有用于分隔符的制表符和空格,我将行更改为:

df = pd.read_csv('Water level.txt',sep = '[" "|\t]',encoding='GBK',engine = 'python')

但它警告:

pandas.errors.ParserError: Expected 14 fields in line 4,saw 16. Error Could possibly be due to quotes being ignored when a multi-char delimiter is used.

使用 Python 将其转换为 CSV 文件的正确方法是什么?

解决方法

如果数据结构没有改变,请尝试传入列宽。 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_fwf.html 此处还有其他选项以及 read_fwf

验证宽度参数是否正确:

pd.read_fwf('JcP65rQY5F2Y.txt',widths=[5,10,9,2,5])


    Unnamed: 0  Unnamed: 1  Unnamed: 2  Unnamed: 3 Unnamed: 4
0        09:25        7.54         288          17        NaN
1        09:30        7.55          20           6        NaN
2        09:30        7.55           7           2       East
3        09:30        7.55          11           3       East
4        09:30        7.56           5           4       West
..         ...         ...         ...         ...        ...
194      09:59        7.60           3           1       East
195      09:59        7.60           9           4       East
196      09:59        7.60           8           1       West
197      09:59        7.60          51           3       West
198      09:59        7.59          20          15       East

[199 rows x 5 columns]
,

您的正则表达式需要调整,`r"[ \t]+" 选择任意长度的空格和制表符(1 或更大)。此外,pandas 使用文件的第一行来确定有多少列。您的示例从 4 列开始,然后添加另一列。太晚了——pandas 已经创建了 4 个元素行。你可以通过提供你自己的列名来解决这个问题,让熊猫知道到底有多少。在本例中,我只使用整数,但您可以为它们指定更有用的名称。

df = pd.read_csv('Water level.txt',sep=r'[ \t]',encoding='GBK',engine='python',names=range(5))