python-3.x - 如何通过在 Python 中使用正则表达式过滤来打印准确的句子
问题描述
我是正则表达式的新手,被下面的代码卡住了。
import re
s = "5. Consider the task in Figure 8.11, which are balanced in fig 99.2"
output = re.findall((r'[A-Z][a-z]*'), s)[0]
output2 = re.findall(r'\b[^A-Z\s\d]+\b', s)
mixing = " ".join(str(x) for x in output2)
finalmix = output+" " + mixing
print(finalmix)
在这里,我试图从给定的字符串 s' 中打印“考虑图 8.11 中的任务,在图 99.2 中平衡”作为输出中的一个句子。因此,我在最后使用 join 语句将两个输出连接起来,将其作为一个句子。但是现在它很令人困惑,因为“图 8.11”和“图 99.2”将不会被打印,因为我没有为此提供正则表达式代码,因为我无法确定我应该使用什么正则表达式,然后在最后组合它。
这可能是因为我使用错误的方法从字符串 s 打印给定的句子。如果有人可以帮助我修复代码或指导我使用其他方法,我会很高兴,因为这段代码看起来很荒谬。
这是我得到的输出:
Consider the task in . which are balanced in .
解决方案
要捕获所有项目符号,我会使用:
import re
s = "5. Consider the task in Figure 8.11, which are balanced in fig 99.2"
items = re.findall(r'\d+\.(?!\d)(.*?)(?=\d+\.(?!\d)|$)', s, flags=re.DOTALL)
print(items)
这打印:
['Consider the task in Figure 8.11, which are balanced in fig 99.2']
以下是正则表达式模式的解释:
\d+\. match a bulleted number
(?!\d) which is NOT followed by another number
(.*?) match and capture all content, across newlines, until hitting
(?=\d+\.(?!\d)|$) another number bullet OR the end of the input
推荐阅读
- python - 我有一个有 4 个角的多边形,而不是一个正方形。如何在python中获得较小部分的纬度和经度?
- mongodb - $match 并在 MongoDB 中 $unwind 之后更新对象中的某个键
- php - 需要 TCPDF 的空白页
- c# - 我在数据集中有两个数据表。我通常登录和退出。当我回去时,其中一个数据表是空的
- reactjs - 如何解决 Reactstrap Navbar 代码问题
- c - 使用 C 将键盘键向右移动 2 位的方法
- java - 多次打印到文件缓冲阅读器java
- ios - 使用 NSFetchedResultsController 在 UITableView 中插入/删除
- javascript - 在插入之前执行获取数据
- amazon-web-services - Terraform - 加载模块时出错 - 没有这样的文件或目录(文件夹重命名后)