Skip to main content
 首页 » 编程设计

python之从句子中查找并删除一个单词(在单词匹配之间)python

2025年05月04日14pander-it

我有如下句子

mainsentence="My words aren't available give didn't give apple and did happening me" 
 
stopwords=['are','did','word', 'able','give','happen'] 

如果有任何单词与中间的单词匹配则想要删除(例如:“word”应该匹配“words”并删除它,“did”应该匹配“didn't”并删除它,“able”应该删除“available” "因为 'able' 词在 'available' 中

finalsentence="My apple and me" 

尝试了下面的代码但是

querywords = mainsentence.split() 
resultwords  = [word for word in querywords if word.lower() not in stopwords] 
result = ' '.join(resultwords) 
print(result) 

但它只适用于完全匹配。

请帮帮我。

请您参考如下方法:

您可以执行以下操作:

>>> ' '.join([word for word in mainsentence.split() if not any([stopword in word for stopword in stopwords])]) 
'My apple and me' 

编辑:这不需要双向检查,只看单词是否包含停用词
EDIT2:使用更新的问题参数更新结果

不区分大小写的版本:

' '.join([word for word in mainsentence.split() if not any([stopword.lower() in word.lower() for stopword in stopwords])])