从列表中选择以特定字符串格式开头的项目
Selecting items from a list that start with a particular string format
我有什么:我通过抓取 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. 等开头并将列表中的其他项目附加到前面的元素的列表列表中的:
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 的最后一个元素这样的情况下这对我没有帮助。感谢任何帮助。
此解决方案将列表组合成单个文本字符串,然后使用 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']
更新:
将捕获组添加到正则表达式以保留行号
我有什么:我通过抓取 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. 等开头并将列表中的其他项目附加到前面的元素的列表列表中的:
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 的最后一个元素这样的情况下这对我没有帮助。感谢任何帮助。
此解决方案将列表组合成单个文本字符串,然后使用 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']
更新: 将捕获组添加到正则表达式以保留行号