gpt4 book ai didi

python - 将文本文件中单独标题下的列保存到单独的列表中

转载 作者:行者123 更新时间:2023-11-30 23:13:27 24 4
gpt4 key购买 nike

我有以下文本文件:

File A
am001 G13
am002 U13
am003 A15

File B
am001 C15
am002 U2715
am003 G32

我想将单独标题下的列值保存到单独的列表中。例如,输出应如下所示:

filea_id = ['am001', 'am002', 'am003']
filea_values = ['G13', 'U13', 'A15']
fileb_id = ['am001', 'am002', 'am003']
fileb_values = ['C15', 'U2715', 'G32']

如何使用 python 来做到这一点?

最佳答案

这是一个经典的例子,itertools 满足了它的期望。

实现

def foo():
from itertools import izip, imap, takewhile
with open("temp.txt") as fin:
def skip(fin):
# Take/Read all lines from the file and discard which are empty
takewhile(lambda name: name.strip() == "", fin)
try:
while fin:
# Skip all empty lines
skip(fin)
# The next line is the file name
fname = next(fin).strip()
# All subsequent lines until the empty line is the content
# Split the lines and transpose it
# Yield the file name and the transposed content
yield fname, zip(*(imap(str.split, takewhile(lambda n:n.strip(), fin))))
except StopIteration:
pass

演示

>>> content ={}
>>> for fname, data in foo():
content[fname]=data


>>> content
{'File A': [('am001', 'am002', 'am003'), ('G13', 'U13', 'A15')], 'File B': [('am001', 'am002', 'am003'), ('C15', 'U2715', 'G32')]}

说明

[Skip All Empty Lines]                                  [Split each line]     [Transpose]      
V
V
[The Next Line is the File Name] fname = File A
[Read Until an empty line] am001 G13 am001 | G13 am001 am002 am003
V am002 U13 >>> am002 | U13 >>> G13 U13 A15
V am003 A15 am003 | A15
[Skip All Empty Lines]
V
V
[The Next Line is the File Name] fname = File B
[Read Until an empty line] am001 C15 am001 | C15 am001 am002 am003
V am002 U2715 >>> am002 | U2715 >>> C15 U2715 G32
V am003 G32 am003 | G32

关于python - 将文本文件中单独标题下的列保存到单独的列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29315292/

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