如何使用python获取文本文件中的表格格式数据
我有一个文本文件中的表格数据,所以我尝试使用python获取数据,但我找不到每列之间的分隔符。请帮帮我。 提前谢谢 数据可能如下所示:如何使用python获取文本文件中的表格格式数据,python,python-3.x,Python,Python 3.x,我有一个文本文件中的表格数据,所以我尝试使用python获取数据,但我找不到每列之间的分隔符。请帮帮我。 提前谢谢 数据可能如下所示: Column1 Column2 Column3 Column4 ---------------------------------------------------------------------------- apple fruits banana fruits orange f
Column1 Column2 Column3 Column4
----------------------------------------------------------------------------
apple fruits banana fruits orange fruits grapes fruits
mango fruits pineapple fruits blackberry fruits
blueberry fruits currant fruits papaya fruits
chico fruits peach fruits pear fruits
我的预期结果是字典格式。我的假设是数据在每个记录的相同列上对齐 我将标题行和一个典型行放在两个distict变量中,您将从文件中读取它们
>>> a = 'Column1 Column2 Column3 Column4'
>>> b = 'apple fruits banana fruits orange fruits grapes fruits'
i
是标题中的索引列表,最初为空,内部
表示我们在列名中
>>> i = []
>>> inside = False
>>> for n, c in enumerate(a):
... if c == ' ':
... inside = False
... continue
... if not inside:
... inside = True
... i.append(n)
>>> i
[0, 18, 38, 58]
我们计算字符数并检查是否在列名的开头
>>> i = []
>>> inside = False
>>> for n, c in enumerate(a):
... if c == ' ':
... inside = False
... continue
... if not inside:
... inside = True
... i.append(n)
>>> i
[0, 18, 38, 58]
我们有列开始的索引,下一列的开始在切片表示法中也是当前列的结束——我们只需要最后一列的结束,但使用切片表示法我们可以使用值None
>>> [b[j:k].rstrip() for j, k in zip(i,i[1:]+[None])]
['apple fruits', 'banana fruits', 'orange fruits', 'grapes fruits']
当然,您必须对输入文件中的每个数据行应用相同的索引技巧
注意:您可能需要使用中的itertools.zip\u longest
方法
[... for j, k in itertools.zip_longest(i, i[1:])]
您可能希望缓存生成器,以避免为每个数据行实例化它
cached_indices = list(itertools.zip_longest(i, i[1:]))
for line in data:
c1, c2, c3, c4 = [... for i, j in cached_indices]
我试图实现我在下面的评论中提出的建议,这是我最大的努力
$ cat fetch.py
from itertools import count # this import is necessary
from io import StringIO # this one is needed to simulate an open file
# Your data, notice that some field in the last two lines is misaligned
data = '''\
Column1 Column2 Column3 Column4
----------------------------------------------------------------------------
apple fruits banana fruits orange fruits grapes fruits
mango fruits pineapple fruits blackberry fruits
blueberry fruits currant fruits papaya fruits
chico fruits peach fruits pear fruits
'''
f = StringIO(data) # you may have something like
# f = open('fruitfile.fixed')
# read the header line and skip a line
header = next(f).rstrip()
next(f) # skip a line
# a compact way of finding the starts of the columns
indices = [i for i, c0, c1 in zip(count(), ' '+header, header)
if c0==' ' and c1!=' ']
# We are going to reuse zip(indices, indices[1:]+[None]), so we cache it
ranges = list(zip(indices, indices[1:]+[None]))
# we are ready for a loop on the lines of the file
for nl, line in enumerate(f, 3):
if line == '\n': continue # don't process blank lines
# extract the _raw_ fields from a line
fields = [line[i:j] for i, j in ranges]
# check that a non-all-blanks field does not start with a blank,
# check that a field does not terminate wit anything but a space
# or a newline
if any((f[0]==' ' and f.rstrip()) or f[-1] not in ' \n' for f in fields):
# signal the possibility of a misalignment
print('Possible misalignment in line n.%d:'%nl)
print('\t|'+header)
print('\t|'+line.rstrip())
# the else body is executed if all the fields are OK
# what I do with the fields is just a possibility
else:
print('Data Line n.%d:'%nl)
fields = [field.rstrip() for field in fields]
for nf, field in enumerate(fields, 1):
print('\tField n.%d:\t%r'%(nf, field))
$python3 fetch.py
数据行n.3:
第1栏:“苹果果实”
第2栏:“香蕉水果”
第3栏:“橙色水果”
第4栏:“葡萄和水果”
数据行n.4:
第1栏:“芒果果实”
第2栏:“菠萝水果”
字段n.3:“”
字段n.4:“黑莓水果”
第n.5行中可能出现的偏差:
|第1列第2列第3列第4列
|蓝莓果醋栗果木瓜果
第n.6行中可能出现的偏差:
|第1列第2列第3列第4列
|奇科水果桃水果梨水果
$
列的起始位置[0,18,38,58]
的魔力在我的答案中也起了作用,但它基于numpy.genfromtxt()
您是否尝试过制表(\t
)?此外,发布用于获取数据的代码可能会有所帮助。Can use可能会遗漏行中的一列,如芒果水果菠萝水果黑莓水果
,应该是4columns@EvgenyPogrebnyak不,我要买[“芒果水果”、“菠萝水果”、“黑莓水果”]
,也就是说,一个(或多个)列表元素将是空字符串。我明白了,很好!也许可以重命名i
以提高可读性,我有一个类似变量的start
。@EvgenyPogrebnyak即使某一行是空的,我也会得到空字符串,因为超出范围的片段总是对应空字符串。对于i
vsstart
,我会更大胆地使用column\u start
,但我来自这样一个时代:每个保存的位都有一个值。。。严重的是,我更喜欢用较短的名称来表示那些非常地方性的东西,它们的意图几乎是不言而喻的。谢谢你们。如果这些值与列标题放错了位置怎么办。这可能会变得棘手。。