如何将空行之前的打开文件中的行追加到字典中,然后继续追加以下行直到下一个空行?

How to append lines in open file before empty line to a dictionary, and then continue appending the following lines until the next empty line?

编码初学者,在此先感谢!

我有一个像这样的文本文件:

A
B
1
2

C
D
1
2
3
4

E
F
1
2
3
4
5
6

我想做的是生成一个字典,将空行之前的每个部分变成一个键值对。例如,我的文本文件字典应该是:

{('A','B'): [[1],[2]], ('C','D'):[[1, 3], [2, 4]], ('E','F'):[[1, 3, 5],[2, 4, 6]]}

现在,我这样开始我的功能:

while line != '':
    # rest of function to append to dictionary here

但我意识到这只适用于第一个空行。如果我尝试继续阅读并打印函数后的行,由于 while 循环的性质,打印的第一行是 D 而不是 C。如何在不导入任何内容的情况下解决这个问题?

这是一种方法(假设文件结构与您所说的完全一样):

首先创建一个包含所有行的字符串:

lines = ''.join(list(open("test.txt")))
#'A\nB\n1\n2\n\nC\nD\n1\n2\n3\n4\n\nE\nF\n1\n2\n3\n4\n5\n6'

然后分成两对:

pairs = lines.split('\n\n')
#['A\nB\n1\n2', 'C\nD\n1\n2\n3\n4', 'E\nF\n1\n2\n3\n4\n5\n6']

最终在每对拆分键和值中:

pairs = lines.split('\n\n')
result = {}
for pair in pairs:
    data = pair.split('\n')
    key = (data[0], data[1])
    first_value = data[2::2]
    second_value = data[3::2]
    result[key] = [first_value, second_value]
result

输出:

{('A', 'B'): [['1'], ['2']],
 ('C', 'D'): [['1', '3'], ['2', '4']],
 ('E', 'F'): [['1', '3', '5'], ['2', '4', '6']]}

注:data[2::2]表示数组切片从位置2开始,每2个元素迭代一次

这样做:

txt = x.read_text() # read file as string here
txt = txt.split('\n\n')
txt = list(map(lambda y: y.split('\n'), txt))

keys = list(map(lambda y: y[:2], txt))
values = list(map(lambda y: y[2:], txt))
d = {tuple(key): [[value[0::2]], [value[1::2]]] for key in keys for value in values}