用字数代替较长的句子

Replacing Longer Sentence With Word Count

我想知道如何用字数替换较长的句子(5 个或更多字)。

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

如果我这样做:

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

print(numsentences)

我知道字数了。但我不知道如何让整个列表显示出现 4 个或更少单词的句子,而 5 个或更多单词的句子按字数打印。

然后我尝试了这样的事情:

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

但我显然走错了路

我需要这样的东西:

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

使用列表理解:

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

输出:

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

我可能会通过创建两个列表来做到这一点。

首先创建一个字数列表,然后使用 zip 同时遍历句子和字数。您可以根据您的情况选择包含一个列表或另一个列表中的值。

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

你可以使用map()提取每个句子的字数,并使用zip()将这些字数(n)与原始字符串(o)合并,然后在列表理解中选择两者:

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