Skip to content Skip to sidebar Skip to footer

Python: How Can I Calculate The Average Word Length In A Sentence Using The .split Command?

new to python here. I am trying to write a program that calculate the average word length in a sentence and I have to do it using the .split command. btw im using python 3.2 this i

Solution 1:

In Python 3 (which you appear to be using):

>>> sentence = "Hi my name is Bob"
>>> words = sentence.split()
>>> average = sum(len(word) for word in words) / len(words)
>>> average
2.6

Solution 2:

You might want to filter out punctuation as well as zero-length words.

>>> sentence = input("Please enter a sentence: ")

Filter out punctuation that doesn't count. You can add more to the string of punctuation if you want:

>>> filtered = ''.join(filter(lambda x: x not in '".,;!-', sentence))

Split into words, and remove words that are zero length:

>>> words = [word for word in filtered.split() if word]

And calculate:

>>> avg = sum(map(len, words))/len(words)
>>> print(avg) 
3.923076923076923

Solution 3:

>>> sentence = "Hi my name is Bob"
>>> words = sentence.split()
>>> sum(map(len, words))/len(words)
2.6

Solution 4:

The concise version:

average = lambda lst: sum(lst)/len(lst) #average = sum of numbers in list / count of numbers in list
avg = average([len(word) for word in sentence.split()]) #generate a list of lengths of words, and calculate average

The step-by-step version:

def average(numbers):
    return sum(numbers)/len(numbers)
sentence = input("Please enter a sentence: ")
words = sentence.split()
lengths = [len(word) for word in words]
print 'Average length:', average(lengths)

Output:

>>> 
Please enter a sentence: Hey, what's up?
Average length: 4

Solution 5:

def main():

    sentence = input('Enter the sentence:  ')
    SumAccum = 0
    for ch in sentence.split():
        character = len(ch)
        SumAccum = SumAccum + character

    average = (SumAccum) / (len(sentence.split()))
    print(average)

Post a Comment for "Python: How Can I Calculate The Average Word Length In A Sentence Using The .split Command?"