用字数替换长句

2024-09-28 01:27:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在试图找出如何用字数替换较长的句子(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']

Tags: theinforlentime单词dosentence
3条回答

使用列表理解:

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

相关问题 更多 >

    热门问题