将文本转换为嵌套列表

Convert a text into a nested list

我正在尝试将文本拆分为多个列表。我尝试了几种方法,但都没有成功。

这是一个例子:

text_1 = "A-0  100  20  10  A-1  100  12  6  A-2  100  10  5"

我想要的结果如下:

[['A-0', '100', '20', '10'], ['A-1', '100', '12', '6'], ['A-2', '100', '10', '5']]

我使用正则表达式将 A- 识别为拆分的分隔符。但是,我正在努力拆分它。也许有更好的方法来解决这个问题?

这只是一个示例,因为我用于 PDF 数据提取器的解决方案是我设法构建的。

如果你知道你总是有 4 组,可以玩 zipiter

x = iter(text_1.split())

然后

list(zip(*[x]*4)) # or list(zip(x,x,x,x))

产量

[('A-0', '100', '20', '10'),
 ('A-1', '100', '12', '6'),
 ('A-2', '100', '10', '5')]

我认为使用内置字符串方法 .split 可能会更容易一些。有了它,您可以执行以下操作:

# Add whitespace at the end of text_1 so that 
# the final split will be the same format as all other splits

text_1="A-0 100 20 10 A-1 100 12 6 A-2 100 10 5" + " "


step1 = text_1.split("A-")

# [1:] here because we want to ignore the first empty string from split
step2 = ["A-" + i for i in step1[1:]] 

# [:-1] here because we know the last element in the new split will always be empty 
# because of the whitespace before the next "A-"
final = [i.split(' ')[:-1] for i in step2]

决赛将是:

[['A-0', '100', '20', '10'], 
['A-1', '100', '12', '6'], 
['A-2', '100', '10', '5']]

这适用于任意大小的列表。

这是我的解决方案:

text_1 = "A-0  100  20  10  A-1  100  12  6  A-2  100  10  5"
# split text by space
text_array = text_1.split()
# result: ['A-0', '100', '20', '10', 'A-1', '100', '12', '6', 'A-2', '100', '10', '5']

# get array length
text_array_size = len(text_array)
# which is 12 in this case
formatted_text_array = []

# create a loop which runs 3 times and split youre array 4 by 4
for i in range(int(text_array_size/4)):
    formatted_text_array.append(text_array[i*4:i*4+4])

print(formatted_text_array)
# result: [['A-0', '100', '20', '10'], ['A-1', '100', '12', '6'], ['A-2', '100', '10', '5']]

如果你想使用正则表达式(正则表达式很酷)并且每个子列表中的项目数量是动态的,试试这个:

import re
text_1 = "A-0  100  20  10  A-1  100  12  6  A-2  100  10  5"
my_list = re.findall(r'A-[^A]*', text_1)
for i in range(0, my_list.__len__()):
    my_list[i] = my_list[i].split()
print(my_list)

基于正则表达式的方法 –– 因为您已经将正则表达式用于您的解决方案:

代码

from re import split

def split_lst(regex, string):
  return filter(lambda x: x.strip(), split(regex, string))

text_1 = "A-0  100  20  10  A-1  100  12  6  A-2  100  10  5"

print(list(map(
  lambda x: list(split_lst(r"\s", x)), 
  split_lst(r"(A-\d+\s+\d+\s+\d+\s+\d+)", text_1)
)))

结果

[['A-0', '100', '20', '10'], ['A-1', '100', '12', '6'], ['A-2', '100', '10', '5']]

Repl.it link