从列表中选择以特定字符串格式开头的项目

时间:2020-12-30 18:36:00

标签: python list formatting

我有什么:我从抓取 PDF 中得到的逐项列表,但是列表的某些元素在列表的相邻元素之间分布不正确

A = ["1. 100 Test.1; 200 Test.2; 300 ", 
     "Test.3; 400 Test.4", 
     "2. 500 Test.5; 600 Test.6;", 
     "3. 700 Test.7; 800 Test.8; ", 
     "900 Test.9; 1000 Test.10"]

我需要什么:以项目 1.、2.、3. 等开头的列表,并将列表中的其他项目附加到列表的前一个元素:< /p>

B = ["1. 100 Test.1; 200 Test.2; 300 Test.3; 400 Test.4", 
     "2. 500 Test.5; 600 Test.6;", 
     "3. 700 Test.7; 800 Test.8; 900 Test.9; 1000 Test.10"]

我尝试过的:我希望找到一种方法来识别列表中格式为“X.X”的项目,但我运气不佳。我确实编写了一个循环来识别列表的元素是否以整数开头,但是在列表 A 的最后一个元素等情况下这对我没有帮助。感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

此解决方案将列表组合成单个文本字符串,然后使用 re.split() 来查找要拆分的 x.x 模式。

import re
import pprint

A = ["1. 100 Test.1; 200 Test.2; 300 ",
     "Test.3; 400 Test.4",
     "2. 500 Test.5; 600 Test.6;",
     "3. 700 Test.7; 800 Test.8; ",
     "900 Test.9; 1000 Test.10"]

# Combine list into a single string
text = "".join(A)

# Split the string into list elements based on desired pattern
lines = re.split(r'(\d\.\s)', text)

# Remove any blank lines
lines = [l for l in lines if l.strip()]

# Combine the line numbers and their matching strings back together
numbered_lines = []
for i in range(0, len(lines), 2):
    numbered_lines.append(lines[i] + lines[i+1])

# Print the results
pprint.pprint(numbered_lines)

输出:

❯ python main.py
['1. 100 Test.1; 200 Test.2; 300 Test.3; 400 Test.4',
 '2. 500 Test.5; 600 Test.6;',
 '3. 700 Test.7; 800 Test.8; 900 Test.9; 1000 Test.10']

更新: 向正则表达式添加捕获组以保留行号