python - 使用正则表达式解析文本以提取有效段落

标签 python regex

如何使用正则表达式解析 python 上的文本,以从诸如此类的内容中提取有效的段落

near accomodation\n\nNear accomodation is one case of accomodation. By changing the shape of the lens, accomodation adjusts the refractory power to the distance of an object under observation. The issue is

我要提取

Near accomodation is one case of accomodation. By changing the shape of the lens, accomodation adjusts the refractory power to the distance of an object under observation.

这意味着有效文本应该以句点结尾,并去掉诸如“The issues is”之类的内容(这是一个未完成的句子)以及任何出现在字符(如\n)之前的内容。

另一个例子是

<p>The level of dopamine available in nerve terminals is controlled by the enzyme monoamineoxidase, which inactivates the neurotransmitter in the presynapse. </p>\n\n</body></html>

应该提取哪个

The level of dopamine available in nerve terminals is controlled by the enzyme monoamineoxidase, which inactivates the neurotransmitter in the presynapse.

所以也去掉任何 html 标签

所以我需要以句点结尾的干净段落。相关段落之前或之后没有任何换行符或 html 标签。所有段落都或多或少类似于我提供的示例。

最佳答案

我建议将删除 HTML 标签(您应该 not do with regex )与主要任务分开,例如 with this solution.

剩下的任务可以使用以下正则表达式来解决:

(?:^|\n|\.)(.*\.)

我们首先匹配文本的开头 (^)、新行或文字点。 ?: 只是为了使该组不被捕获。然后我们以贪婪的方式收集所有内容,直到一个点(这意味着我们获得了最大的可能匹配)。

你可以这样使用它:

import re
m = re.findall(r"(?:^|\n|\.)(.*\.)", your_string)
if m:
    print(m[0].strip())

关于python - 使用正则表达式解析文本以提取有效段落,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50659268/

相关文章:

python - 尝试使用 ExchangeLib 返回过去 24 小时内的电子邮件

python - 数字的正则表达式,包括小数和斜线

python - 在轴顶部绘制标记

ruby - 搜索/替换怪异

r - 每> n个字符替换子字符串(有条件地为空格插入换行符)

javascript - 正则表达式替换列表中的 0 但不是 10、20、30 等中的 0 - 使用 js 替换

c++ - 如何在txt文件中搜索正则表达式?

python - 在 Pandas 中循环清理多个文档并将它们保存到一本书中

python - Bamboo 日志输出顺序问题

JavaScript 正则表达式捕获 '%20' 或空格