首页 > 解决方案 > 如何通过在 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 .

标签: python-3.xregex

解决方案


要捕获所有项目符号,我会使用:

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

推荐阅读