Removing list of words from a string

前端 未结 5 2016
一个人的身影
一个人的身影 2020-11-30 06:54

I have a list of stopwords. And I have a search string. I want to remove the words from the string.

As an example:

stopwords=[\'what\',\'who\',\'         


        
5条回答
  •  情歌与酒
    2020-11-30 06:56

    building on what karthikr said, try

    ' '.join(filter(lambda x: x.lower() not in stopwords,  query.split()))
    

    explanation:

    query.split() #splits variable query on character ' ', e.i. "What is hello" -> ["What","is","hello"]
    
    filter(func,iterable) #takes in a function and an iterable (list/string/etc..) and
                          # filters it based on the function which will take in one item at
                          # a time and return true.false
    
    lambda x: x.lower() not in stopwords   # anonymous function that takes in variable,
                                           # converts it to lower case, and returns true if
                                           # the word is not in the iterable stopwords
    
    
    ' '.join(iterable) #joins all items of the iterable (items must be strings/chars)
                       #using the string/char in front of the dot, i.e. ' ' as a joiner.
                       # i.e. ["What", "is","hello"] -> "What is hello"
    

提交回复
热议问题