检查文本文件中不一致列的分隔符,(逗号),并在Python中将数据添加到Excel中

0 投票
2 回答
44 浏览
提问于 2025-04-14 15:51

我有一些文本文件,里面的内容是用逗号 , 分隔的,格式如下。

文本文件的例子:

a,
b,
c,
a,d,b,
k,m,
f,g,h,j,

我需要把这些内容输出到一个Excel文件中,每个文本文件放在不同的工作表里。但是当我用 pd.read_table 读取文件时,遇到了一个解析错误。这个错误是因为某些行的列数不一致,比如在文本文件的第4行,它说预期有2个字段,但实际上看到了4个字段。

a
b
c
a d b
k m
f g h j

我使用的代码如下:

df = pd.read_table("exp.txt",delimiter = ",", header=None)

2 个回答

0

这个问题是因为每一行的列长度不一样。可以把最大列数设置为一个固定的值。试试下面的例子:

import pandas as pd

number_of_max_cols = 4
cols_name = ["co1" + str(i+1) for i in range(number_of_max_cols)]
df = pd.read_table("pl_file.txt",delimiter = ",", names=cols_name, header=None)
print(df)

输出结果:

  co11 co12 co13 co14
0    a  NaN  NaN  NaN
1    b  NaN  NaN  NaN
2    c  NaN  NaN  NaN
3    a    d    b  NaN
4    k    m  NaN  NaN
5    f    g    h    j
1

你的问题是因为你有一个不固定数量的字段。

我看到有两种解决办法。第一种是你提前知道列的数量(或者至少知道一个上限),这样你就可以指定这些列:

N_COLs = 10
df = (pd.read_csv(your_file, sep=',', names=range(N_COLs))
        .dropna(how='all', axis=1) # optional, to drop empty columns
     )

第二种是你不知道列的数量,你可以传一个不存在的分隔符,这样就可以把所有内容放在一列里,然后用 split 来分开:

df = (pd.read_csv(your_file, sep='--NOSEP--', header=None, engine='python')[0]
        .str.strip(', ').str.split(',', expand=True)
     )

注意:第二种方法在处理带引号的字段时无法正确解析CSV,这种方法只适用于简单的 , 分隔符。

输出结果:

   0     1     2     3
0  a  None  None  None
1  b  None  None  None
2  c  None  None  None
3  a     d     b  None
4  k     m  None  None
5  f     g     h     j

撰写回答