python-3.x 用一个函数计算短语的平均字母长度

dw1jzc5e  于 2022-12-05  发布在  Python
关注(0)|答案(1)|浏览(100)

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

# 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
w41d8nur

w41d8nur1#

或者,该程序可简化为以下函数:你原来的程序只是把它弄得过于复杂。

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.4

相关问题