gpt4 book ai didi

python - 有效地计算文本文件的列数

转载 作者:太空宇宙 更新时间:2023-11-04 10:33:26 25 4
gpt4 key购买 nike

我有一堆大的制表符分隔的文本文件,格式类似于:

a   0.0694892   0   0.0118814   0   -0.0275522  
b 0.0227414 -0.0608639 0.0811518 -0.15216 0.111584
c 0 0.0146492 -0.103492 0.0827939 0.00631915

统计我一直用的列数:

>>> import numpy as np
>>> np.loadtxt('file.txt', dtype='str').shape[1]
6

但是,这种方法对于较大的文件显然效率不高,因为整个文件内容在获取shape 之前被加载到数组中。有没有更简单、更高效的方法?

最佳答案

你不需要 numpy;只需阅读一行,将其拆分为制表符并找到列表的长度:

with open('file.txt', 'rb') as f:
line = next(f) # read 1 line
n = len(line.split('\t'))

如果以后你想加载整个数组,你可以这样做:

f.seek(0)
arr = np.loadtxt(f)

关于python - 有效地计算文本文件的列数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25004180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com