热门

最新

红包

立Flag

投票

同城

我的

发布
jailman
大囚长
3 年前
truejailman

import re
text = """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 re
import itertools
text = """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)] # 找到所有符合正则表达式的位置,并在开头加上0
for 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])

CSDN App 扫码分享
分享
评论
点赞
打赏
  • 复制链接
  • 举报
下一条:
上班
立即登录