python - 从 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
也许可以帮助标记化?
解决方案
您可以将正则表达式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"
推荐阅读
- spring-boot - 重新启动我的 Spring Boot 应用程序后,Redis 数据在 Docker 中被删除
- python - Pandas - 创建新列,其中值取自同一数据框中的其他行
- flask - 如何将 slackapi 发布结果从 Flask 返回到 slackchannel?
- r - 使用纬度和经度匹配密码(印度)
- python - matplotlib set_yticks 去掉 imshow 的上下半行
- c++ - 参数中的前向声明与“正常”前向声明之间的区别
- angular - Angular 6 声明方法的类型
- c# - 使用 NAN 作为未定义值
- uwp - UWP中使用多张图片生成动态动画
- vb.net - 使用 URI 格式打开文件