首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在关键词python出现后使用regex删除语句

在关键词python出现后使用regex删除语句
EN

Stack Overflow用户
提问于 2021-05-27 13:30:18
回答 2查看 51关注 0票数 2

我正在寻找一个正则表达式的解决方案,以删除在关键短语出现后的其余句子中的任何单词。

示例

句子=“今天的天气预报主要是晴天。明天的天气预报是下雨。这周剩下的时间.”

Key_phrase =“明天”

预期产量=“今天的天气预报主要是晴天。天气预报。这周剩下的时间.”

尝试

代码语言:javascript
复制
head, sep, tail = sentence.partition(key_phrase)
print(head)

我的想法是先将字符串拆分成句子,然后应用上述技巧,然后加入结果。然而,我觉得一定有一个更优雅的方法来做这个与regex?

谢谢你的帮助

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-05-27 13:36:41

使用re.sub

Ex:

代码语言:javascript
复制
sentence = "The weather forecast for today is mostly sunny. The forecast for tomorrow will be rainy. The rest of the week..."
key_phrase = "for tomorrow"
print(re.sub(fr"({key_phrase}.*?)(?=\.)", "", sentence))

输出

代码语言:javascript
复制
The weather forecast for today is mostly sunny. The forecast . The rest of the week...
票数 2
EN

Stack Overflow用户

发布于 2021-05-27 20:39:36

使用

代码语言:javascript
复制
re.sub(fr"{re.escape(key_phrase)}[^.]*", "", sentence)

正则证明

解释

代码语言:javascript
复制
--------------------------------------------------------------------------------
  for                      'for'
--------------------------------------------------------------------------------
  \                        ' '
--------------------------------------------------------------------------------
  tomorrow                 'tomorrow'
--------------------------------------------------------------------------------
  [^.]*                    any character except: '.' (0 or more times
                           (matching the most amount possible))

请参阅Python证明

代码语言:javascript
复制
import re
sentence = "The weather forecast for today is mostly sunny. The forecast for tomorrow will be rainy. The rest of the week..."
key_phrase = "for tomorrow"
print(re.sub(fr"{re.escape(key_phrase)}[^.]*", "", sentence))

结果The weather forecast for today is mostly sunny. The forecast . The rest of the week...

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67723222

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档