首页 > 解决方案 > 从 Python 中的句子中删除单词而不是子词

问题描述

我需要从 Python 中的句子(给定字符串)中删除给定的单词向量。

问题是我想删除确切的单词而不是子字符串或子词。

注意:我不能假设单词之前或之后有空格

我尝试了该.replace(word,"")功能但无法正常工作

例子:s = "I'am at home and i will work by webcam call"

当我做s.replace("am","")

输出:i' at home and i will work by webc call

也许可以帮助标记化?

标签: pythonstringmachine-learningnlprecurrent-neural-network

解决方案


您可以将正则表达式re.sub与单词边界\b字符一起使用:

>>> import re
>>> s = "I'am at home and i will work by webcam call"
>>> re.sub(r"\bam\b", "", s)
"I' at home and i will work by webcam call"

使用单词列表,您可以使用循环,或使用|,例如从多个单词构建析取"am|and|i"。可选择使用re.I标志忽略大写/小写:

>>> words = ["am", "and", "i"]
>>> re.sub(r"\b(%s)\b" % "|".join(words), "", s, flags=re.I)
"' at home   will work by webcam call"

推荐阅读