How to remove list of words from a list of strings

后端 未结 4 783
情深已故
情深已故 2020-12-13 11:19

Sorry if the question is bit confusing. This is similar to this question

I think this the above question is close to what I want, but in Clojure.

There is a

4条回答
  •  [愿得一人]
    2020-12-13 12:02

    Here is my stab at it. This uses regular expressions.

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

    Sans lambda:

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

    Update

    Fix for the bug pointed out by gnibbler (thanks!):

    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: the above change avoids snipping off the trailing "in" from "Spain". To verify run both versions of the regular expressions against the phrase "Spain has rain".

提交回复
热议问题