【发布时间】:2020-11-06 08:27:25
【问题描述】:
我正在尝试查找不紧跟在the 之前的单词。
执行积极的回溯以获取关键字“the”(?<=the\W) 之后的单词。但是,我无法捕捉到“人”和“那个”,因为上述逻辑不适用于这些情况。
我无法处理前后没有关键字“the”的单词(例如,句子中的“that”和“people”)。
p = re.compile(r'(?<=the\W)\w+')
m = p.findall('the part of the fair that attracts the most people is the fireworks')
print(m)
目前得到的输出是
'part','fair','most','fireworks'.
编辑:
感谢您在下面提供的所有帮助。使用 cmets 中的以下建议,设法更新了我的代码。
p = re.compile(r"\b(?!the)(\w+)(\W\w+\Wthe)?")
m = p.findall('the part of the fair that attracts the most people is the fireworks')
这让我更接近我需要得到的输出。
更新的输出:
[('part', ' of the'), ('fair', ''),
('that', ' attracts the'), ('most', ''),
('people', ' is the'), ('fireworks', '')]
我只需要字符串('part','fair','that','most','people','fireworks')。 有什么建议吗?
【问题讨论】:
标签: python python-re lookbehind