簡體   English   中英

python 正則表達式使用 re 模塊(不是正則表達式模塊)獲取文本的最后一個單詞,直到停止詞

[英]python regex get last words of a text up to a stop word with re module (not regex module)

我在將文本的最后一句話變成停用詞之后。

想象一下我有文字:

first_part = "This is a text that with the blue paper"

從頭回來我想得到“藍皮書”。

為了做到這一點,我使用了正則表達式模塊

import regex as re
print(first_part)
result=re.search(r"(?r)(?<=(\s*\b(an|a|the|for)\b\s*))(?P<feature>.*?)(?=\s*)$",first_part)
print(result)

正則表達式解釋:
(?r) = 反向
(?<=(\s*\b(an|a|the|for)\b\s*)) =查看任何帶有單詞邊界的停用詞 \b
(?P 特征。 ?) = 基本上是什么。
$ = 從字符串的末尾

這工作得很好。 但我正在使用模塊正則表達式,以便能夠使用“(?r)”表示反向。

任何人都知道是否可以使用 re 來做到這一點? 我需要使用標准庫功能來實現此功能。

如果你在前面添加一個貪婪匹配,在后面添加一個惰性匹配,你只會得到最后的話。雖然不是 100% 確定這是你想要的。

>>> first_part = "This is a text that with the blue paper"
>>> m = re.match(r"(?:.*)(?:an|a|the|for)\W(.+?)$", first_part)
>>> m[1]
'blue paper'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM