【发布时间】:2026-02-09 08:35:01
【问题描述】:
我有一个包含数百万个单词的字符串,我想要一个正则表达式,它可以返回任何美元符号周围的五个单词。例如:
string = 'I have a sentence with $10.00 within it and this sentence is done. '
我希望正则表达式返回
surrounding = ['I', 'have', 'a', 'sentence', 'with', 'within', 'it', 'and', 'this', 'sentence']
我的最终目标是统计所有围绕提及“$”的单词,因此上述列表将包含以下内容:
final_return = [('I', 1), ('have', 1), ('a', 1), ('sentence', 2), ('with', 1), ('within', 1), ('it', 1), ('and', 1), ('this', 1)]
到目前为止我开发的下面的正则表达式可以返回附加到货币符号的字符串以及周围的 5 个字符。有没有办法编辑正则表达式来捕获周围的五个单词?我应该(如果是的话,如何)使用 NLTK 的标记器来实现这一点?
import re
.....\$\s?\d{1,3}(?:[.,]\d{3})*(?:[.,]\d{1,2})?.....
【问题讨论】:
-
你能导入
regex模块吗?
标签: python regex python-3.x tokenize