如何使用正则表达式解析 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/