Search code examples
pythonstringnlp

how to get string with maximum of three words in a list of strings


I have a list of different strings with different number of words in each string, I want to be able to get string with maximum of three words from the list,

This is the list of strings below

['organised crimes perpetrated globally using sltd .“',
 'major system supporting arm manned',
 'united states national central bureau',
 'interpol police global system',
 'national central bureau',
 'global community .“',
 'tracking system domiciled',
 'interpol global system',
 'nigerian sltd detection',
 'successfully yielded result',
 'statement made available',
 'mr muhammad babandede',
 'lost travel documents',
 'deliberate acts leading']

This is the output I'm expecting Expected output:

['national central bureau',
 'global community .“',
 'tracking system domiciled',
 'interpol global system',
 'nigerian sltd detection',
 'successfully yielded result',
 'statement made available',
 'mr muhammad babandede',
 'lost travel documents',
 'deliberate acts leading']

Thanks in advance


Solution

  • Use str.split and check its length

    sentences = ['organised crimes perpetrated globally using sltd .“', 'major system supporting arm manned',
              'united states national central bureau', 'interpol police global system',
              'national central bureau', 'global community .“', 'tracking system domiciled', 'interpol global system',
              'nigerian sltd detection', 'successfully yielded result', 'statement made available',
              'mr muhammad babandede', 'lost travel documents', 'deliberate acts leading']
    
    result = [sentence for sentence in sentences if len(sentence.split()) <= 3]