Search code examples
pythonloopsfor-looplist-comprehension

Replacing Longer Sentence With Word Count


I am trying to figure out how to replace longer sentence (5 or more words) with the word count.

s = ['Two heads are better than one', 'Time flies', 'May the force be with you', 'I do', 'The Itchy and Scratchy Show', 'You know nothing Jon Snow', 'The cat ran']

If I do this:

numsentences = [len(sentence.split()) for sentence in s]

print(numsentences)

I get the word count. But I don't know how to get the entire list to show up where the sentences with 4 or less words come up, whilst the sentences with 5 or more words get printed by their word count.

I then tried something like this:

sn = []
for sentence in s:
    num if len(sentence.split(i) > 2)

but I am obviously not on the right track.

I need to get something like:

s = [6, 'Time flies', 6, 'I do', 5, 5, 'The cat ran']

Solution

  • Using list comprehension:

    output = [string if len(string.split(' ')) < 5 else len(string.split(' ')) for string in s]
    

    Output:

    [6, 'Time flies', 6, 'I do', 5, 5, 'The cat ran']