import retext = """1. This is the first paragraph.It has two lines.2. This is the second paragraph.It also has two lines.3. This is the last paragraph.It has only one line."""pattern = r'^\d+' # 定义正则表达式,匹配以数字开头的行lst = re.split(pattern, text, flags=re.M) # 将文字按照正则表达式分割为列表,使用多行模式lst.pop(0) # 去掉第一个空元素for i in range(len(lst)): # 遍历列表中的每个元素 print(f'Paragraph {i+1}: {lst[i].strip()}') # 打印每个段落的内容,去掉首尾空白import reimport itertoolstext = """1. This is the first paragraph.It has two lines.2. This is the second paragraph.It also has two lines.3. This is the last paragraph.It has only one line."""pattern = r'^\d+' # 定义正则表达式,匹配以数字开头的行positions = [0] + [m.start() for m in re.finditer(pattern, text, flags=re.M)] # 找到所有符合正则表达式的位置,并在开头加上0for i, g in itertools.groupby(positions, key=lambda x: x > 0): # 根据位置是否大于0将位置分组 if i: # 如果位置大于0 group = list(g) # 将分组转换为列表 start = group[0] # 取出列表中的第一个元素作为起始位置 end = group[-1] # 取出列表中的最后一个元素作为结束位置 print(text[start:end])