在句子中查找单词的出现

时间:2017-04-03 05:29:02

标签: python string python-2.7

我想在句子中找到某个单词的出现然后将其删除。我能够做到这一点,但有时我想删除的词可以是一个子词。例如,我想在“Music is worldwide”中找到/删除“word”一词。我的程序将fin / remove返回一个正值,它在句子中找到单词“word”,而实际上它遇到了“worldwide”这个词,我希望它返回一个负值。 我正在使用

index = text.find(word)

有没有其他方法可以避免这个单词作为句子中的子词的问题?提前谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用正则表达式模块,并依赖正则表达式单词边界(\b)来匹配整个单词。

由于您试图从句子中删除该字词,因此这里有一个用空字符串替换所有匹配项的示例:

import re

sentence = 'Music world is worldwide'
word = 'world'
removed = re.sub(r'\b%s\b' % word, '', sentence)

print removed # prints "Music   is worldwide" 

如果您只是想找到第一次出现的位置,可以按如下方式进行:

import re

sentence = 'Music is worldwide in the world'
word = 'world'
match = re.search(r'\b%s\b' % word, sentence)

if match:
    print match.start() # prints 26

查看re模块的文档以获取详细信息。

答案 1 :(得分:0)

我想在这个词上添加一个空格,即:



word = " "+ word
index = text.find(word)




但我想知道是否有更有效和干净的方法。

相关问题