如何从字符串列表中删除单词列表

pra*_*bhu 9 python regex list-comprehension stop-words

对不起,如果问题有点令人困惑.这与此问题类似

我认为上述问题接近我想要的,但在Clojure中.

还有一个问题

我需要这样的东西,但在那个问题中不是'[br]',而是有一个需要搜索和删除的字符串列表.

希望我清楚自己.

我认为这是因为python中的字符串是不可变的.

我有一个需要从字符串列表中删除的干扰词列表.

如果我使用列表理解,我最终会一次又一次地搜索相同的字符串.所以,只有"of"被删除而不是"the".所以我修改后的列表看起来像这样

places = ['New York', 'the New York City', 'at Moscow' and many more]

noise_words_list = ['of', 'the', 'in', 'for', 'at']

for place in places:
    stuff = [place.replace(w, "").strip() for w in noise_words_list if place.startswith(w)]
Run Code Online (Sandbox Code Playgroud)

我想知道我在做什么错.

Ton*_*nen 15

如果没有正则表达式,你可以这样做:

places = ['of New York', 'of the New York']

noise_words_set = {'of', 'the', 'at', 'for', 'in'}
stuff = [' '.join(w for w in place.split() if w.lower() not in noise_words_set)
         for place in places
         ]
print stuff
Run Code Online (Sandbox Code Playgroud)


Man*_*dan 10

这是我的抨击.这使用正则表达式.

import re
pattern = re.compile("(of|the|in|for|at)\W", re.I)
phrases = ['of New York', 'of the New York']
map(lambda phrase: pattern.sub("", phrase),  phrases) # ['New York', 'New York']
Run Code Online (Sandbox Code Playgroud)

Sans lambda:

[pattern.sub("", phrase) for phrase in phrases]
Run Code Online (Sandbox Code Playgroud)

更新

修复了gnibbler指出的bug (谢谢!):

pattern = re.compile("\\b(of|the|in|for|at)\\W", re.I)
phrases = ['of New York', 'of the New York', 'Spain has rain']
[pattern.sub("", phrase) for phrase in phrases] # ['New York', 'New York', 'Spain has rain']
Run Code Online (Sandbox Code Playgroud)

@prabhu:上述变化避免了从"西班牙"中删除尾随的" in ".要验证运行两个版本的正则表达式对短语"西班牙有雨".