Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need some help finding the length of a word and how many word have that length with tabular. For example, if the sentence is "I will buy a new bike.",

The output would be

Length of Word How Many Words In The Text In This Length
1 1
3 2
4 1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

If you prefer doing it without any imports at all:

def wordlenghtsgrouper(phrase):
    l = [len(w) for w in phrase.replace('.','').replace(',','').split()]
    return {i:l.count(i) for i in l}

It returns a dictionary containing the "lengths" and a count of each ocurrence.

If you don't mind importing, you can use the Counter which is specifically does what you ask for:

from collections import Counter
...
def wordlenghtsgrouper(phrase):
    return Counter([len(w) for w in phrase.replace('.','').replace(',','').split()])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...