pythonpython-3.xaveragestring-lengthletter

Calculate average the letter length of a phrase with one function


I did this programming to calculate the average letters of a phrase. Do you think this program is responsible for all texts? And do you have a better offer? Thanks

# calculate average word length of phrase

print("This program will calculate average word length!")

def length_of_words (string,n): 
    n_words = 0
    words_in_string=string.split() # Separation of words
    for this_word in words_in_string: # count the number of letters for each word
        if len(this_word) == n:
            n_words = n_words + 1
    return n_words
string = input("Please give me a phrase:\n") # get the phrase
s = 0  # Initialize the sum
iteration = 0 # Initialize to count the number of words
for n in range(1,len(string)):
    len_words=length_of_words(string,n)
    if len_words==0:
        continue
    print("the number of",n, "letter is",len_words)
    iteration=iteration+1
    #print(iteration)
    s=n+s
    average=s/iteration # average of word length
    #print(s)
print("The average word length of phrase is", average) # Showing  average

    

Solution

  • Alternatively, this program can be simplified to this function: Your original program just make it overly complex.

    def avg_len(sentence):
        words = sentence.split()  # split this sentence to words
        return sum(len(w) for w in words)/ len(words)  # the avg. word's length
    
    

    Running it:

    >>> avg_len('this is a raining day')
    3.4