10

对不起,如果这个问题有点令人困惑。这类似于这个问题

我认为上述问题接近我想要的,但在 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)]

我想知道我在做什么错误。

4

4 回答 4

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
于 2010-08-18T11:25:18.377 回答
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']

lambda

[pattern.sub("", phrase) for phrase in phrases]

更新

修复gnibbler指出的错误(谢谢!):

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']

@prabhu:上述更改避免了从“西班牙”中剪掉尾随的“ in ”。为了验证对短语“西班牙有雨”运行正则表达式的两个版本。

于 2010-08-18T09:58:58.513 回答
4
>>> import re
>>> noise_words_list = ['of', 'the', 'in', 'for', 'at']
>>> phrases = ['of New York', 'of the New York']
>>> noise_re = re.compile('\\b(%s)\\W'%('|'.join(map(re.escape,noise_words_list))),re.I)
>>> [noise_re.sub('',p) for p in phrases]
['New York', 'New York']
于 2010-08-18T10:04:41.123 回答
1

既然你想知道你做错了什么,这一行:

stuff = [place.replace(w, "").strip() for w in noise_words_list if place.startswith(w)]

发生,然后开始循环单词。首先它检查“of”。检查您的位置(例如“of the New York”)是否以“of”开头。它被转换(调用替换和剥离)并添加到结果列表中。这里的关键是永远不会再次检查结果。对于您在理解中迭代的每个单词,都会将一个新结果添加到结果列表中。所以下一个词是“the”,而你的位置(“of the New York”)不是以“the”开头的,所以不会添加新结果。

我假设您最终得到的结果是您的位置变量的串联。一个更易于阅读和理解的程序版本将是(未经测试):

results = []
for place in places:
    for word in words:
        if place.startswith(word):
            place = place.replace(word, "").strip()
    results.append(place)

请记住,这replace()将删除字符串中任何位置的单词,即使它作为简单的子字符串出现。您可以通过使用具有类似^the\b.

于 2010-08-18T10:13:00.247 回答