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

Categories

0 votes
3.2k views
in Technique[技术] by (71.8m points)

Finding the Length of a Word in a String and Finding How Many Words Have That Length. Without Using Import And NLTK(Python)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.5k users

...