Home > Blockchain >  How to remove sentences/phrases of a certain length from a list?
How to remove sentences/phrases of a certain length from a list?

Time:06-05

So this is a smaller version of my sentences/phrase list:

search = ['More than words', 'this way', 'go round', 'the same', 'end With', 'be sure', 'care for', 'see you in hell', 'see you', 'according to', 'they say', 'to go', 'stay with', 'Golf pro', 'Country Club']

What I would like to do is remove any terms that are more or less than 2 words in length. I basically just want another list with all 2 word terms. Is there a way to do this in Python? From my searching, I have only managed to find how to erase words of a certain number of characters and not entire phrases.

CodePudding user response:

You can get 2 word phrases using this:

ans = list(filter(lambda s: len(s.split()) == 2, search))

Another way is using list comprehension:

ans = [w for w in search if len(w.split()) == 2]

CodePudding user response:

Well if you take a simple approach and say every word must be separated by a space, then any two-word strings will only have 1 space character, three-word strings have 2 space characters, and so on (general rule, an n-word string has (n-1) spaces).

You can just break the two lists up like this (if you want one with strings <= two words, and one with strings > 2 words):

twoWords = []
moreThanTwo = []

for s in search:
    if s.count(" ") == 1:
        twoWords.append(s)
    else
        moreThanTwo.append(s)

Or to simplify with a lambda expression and just extract a single list of all two-word strings:

twoWords = list(filter(lambda s: s.count(" ") == 1, search))

CodePudding user response:

As you want to get a new list with a list of words of length equal to 2, use list comprehension

new_list = [sentence for sentence in search if len(sentence.split(' ')) == 2]
  • Related