从Python中的字符串中删除所有文章,连接词等

Par*_*gue 5 python string

我有一个包含许多句子的列表.我想遍历列表,从所有句子中删除"and","the","a","are"等字样.

我试过这个:

def removearticles(text):


articles = {'a': '', 'an':'', 'and':'', 'the':''}
for i, j in articles.iteritems():
    text = text.replace(i, j)
return text
Run Code Online (Sandbox Code Playgroud)

但是,正如您可能会知道的那样,当它出现在单词的中间时,这将删除"a"和"an".我需要在空格分隔时仅删除单词的实例,而不是当它们在单词内时.最有效的方法是什么?

Nem*_*157 6

我会去正则表达式,如:

def removearticles(text):
  re.sub('(\s+)(a|an|and|the)(\s+)', '\1\3', text)
Run Code Online (Sandbox Code Playgroud)

或者如果你想删除前导空格:

def removearticles(text):
  re.sub('\s+(a|an|and|the)(\s+)', '\2', text)
Run Code Online (Sandbox Code Playgroud)