python - 如何将文本按 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 个元素的列表。
解决方案
您不能仅使用正则表达式来执行此操作,因为正则表达式引擎将文本作为文本进行匹配,并且无法增加或减少找到的数值并在匹配时进行比较。只有在获得所有匹配项后,您才能执行此操作。
我建议使用正则表达式来提取所有项目符号及其相应的数字,然后分析结果并重新构建最终列表:
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.']
详情:
(?:^|\n)
- 字符串或换行符的开头(([0-9]+)\.[\s\S]*?)
- 组 1 匹配([0-9]+)
- 第 2 组:一位或多位数字\.
- 一个点[\s\S]*?
- 尽可能少的任何零个或多个字符
(?=\n[0-9]+\.|\Z)
- 直到最左边的换行符,一个或多个数字,然后是.
(\n[0-9]+\.
) 或字符串结尾 (\Z
)。
推荐阅读
- entity-framework-core-2.1 - Entityframework核心代码先迁移Complex类型
- c - free() 函数只释放结构的第一个元素?
- android - 使用 FirebaseDatabase 加入两个子节点
- c# - 如何在等待 WCF 回调时保持控制台应用程序运行?
- node.js - DynamoDB 与 NodeJS - 获取 ID 不等于第一个查询结果的元素列表
- python - 使用 tensorflow 进行多目标检测和跟踪
- sql-server - 如何更改 CLR 函数中的凭据以使用服务帐户以外的帐户
- sql - 从开始日期创建间隔并表示所有值 - 逗号分隔
- react-native - 你知道从 detox@12 到 detox@13 的重大变化吗?
- django - 在 Django Rest 框架中获取或创建