首页 > 解决方案 > 如何将文本按 1)、2) 拆分?

问题描述

我想按子部分 1.、2.、... 拆分我的文本

import re

s = "1. First sentence. \n2. Second sentence. \n1. Another sentence. \n3. Third sentence."

l = re.compile('\n(?=[0-9].)').split(s)

使用我的正则表达式,我得到: ['1. First sentence. ', '2. Second sentence. ', '1. Another sentence. ', '3. Third sentence.']

但我只想在数量优于前一个的情况下拆分 ['1. First sentence. ', '2. Second sentence. 1. Another sentence. ', '3. Third sentence.']

对于这个例子,我想要一个包含 3 个元素而不是 4 个元素的列表。

标签: pythonregex

解决方案


您不能仅使用正则表达式来执行此操作,因为正则表达式引擎将文本作为文本进行匹配,并且无法增加或减少找到的数值并在匹配时进行比较。只有在获得所有匹配项后,您才能执行此操作。

我建议使用正则表达式来提取所有项目符号及其相应的数字,然后分析结果并重新构建最终列表:

import re
s = "1. First sentence. \n2. Second sentence. \n1. Another sentence. \n3. Third sentence."
l = re.findall(r'(?:^|\n)(([0-9]+)\.[\s\S]*?)(?=\n[0-9]+\.|\Z)', s)
curr_num = 0                  # Init the current number to 0
result = []                   # The final bullet point list
for s,num in l:               # Iterate over the list of results
    if curr_num > int(num):   # If curr_num is greater than the number found
        if not result:        # If it is the first item, 
            result = ['']     #    we need to add an empty item
        result[-1] += s       # Append the text to the last item
    else:                     # else
        result.append(s)      # Append the line to the resulting list
    curr_num = int(num)       # Assign the current number
    
print(result) 
# => ['1. First sentence. ', '2. Second sentence. 1. Another sentence. ', '3. Third sentence.']

请参阅Python 演示正则表达式演示

详情

  • (?:^|\n)- 字符串或换行符的开头
  • (([0-9]+)\.[\s\S]*?)- 组 1 匹配
    • ([0-9]+)- 第 2 组:一位或多位数字
    • \.- 一个点
    • [\s\S]*?- 尽可能少的任何零个或多个字符
  • (?=\n[0-9]+\.|\Z)- 直到最左边的换行符,一个或多个数字,然后是.( \n[0-9]+\.) 或字符串结尾 ( \Z)。

推荐阅读