Home > Software design >  Replacing Longer Sentence With Word Count
Replacing Longer Sentence With Word Count

Time:10-11

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

CodePudding user response:

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

CodePudding user response:

I'd probably do this by creating two lists.

First create a list of word counts, and then iterate through both the sentences and the word counts at the same time using zip. You can choose to include the value from one list or the other based on your condition.

sentences = [
    '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'
]

word_counts = [len(sentence.split(' ')) for sentence in sentences]
reduced_sentences = [
    sentence if word_count < 5 else word_count
    for sentence, word_count in zip(sentences, word_counts)
]

CodePudding user response:

You can use map() to extract the number of words from each sentence, and zip() to combine these word counts (n) with the original strings (o), then chose between the two in a list comprehension:

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

r = [ [o,n][n>4] for o,n in  zip(s,map(len,map(str.split,s)))]

print(r)
[6, 'Time flies', 6, 'I do', 5, 5, 'The cat ran']
  • Related