用一个函数计算一个短语的平均字母长度

Calculate average the letter length of a phrase with one function

我编写这个程序是为了计算一个短语的平均字母数。您认为该程序对所有文本负责吗?你有更好的报价吗?谢谢

# 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

    

或者,这个程序可以简化为这个函数: 你原来的程序让它变得过于复杂。

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

运行它:

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