使用collections.Counter将生成一个类似dict的对象,其中键作为字长,值作为每个长度的字数。在>>> s = 'hello this is a sentence with words of varying lengths'
首先,记录所有单词的长度:
^{pr2}$
然后,数一数上面的字符串中以不同长度出现的单词数:>>> from collections import Counter
>>> word_lengths = Counter(lengths)
>>> word_lengths
Counter({2: 2, 4: 2, 5: 2, 7: 2, 1: 1, 8: 1})
编辑:既然你想要一个累积的总和,那么试试这个:def count_lengths(text, n):
lengths = [len(word) for word in text.split()]
word_lengths = Counter(lengths)
# count the total number of words with lengths less than or equal to n
n_and_less_chars = sum(value for key, value in word_lengths.items() if key <= n)
return n_and_less_chars
尝试一下:>>> print(count_lengths(s, 5))
7
如果我们看一下上面的字符串示例,我们可以看到,实际上有7个单词包含5个或更少的字符。在