2016-02-23 53 views
0
def main(): 
    print() 
    print("Program to calculate the average word length") 
    print("You will be asked to enter a sentence") 
    print("Written by Reilly Peters") 
    print() 


    #lets the user enter a sentence 
    senstr=input("Enter a sentence: ") 
    print()#for turnin 


    #Repeats the the users sentence 
    print() 
    print("Original Sentence:",senstr) 

    #splits the sentence into a list 
    sen = senstr.split() 
    for ch in senstr.split(): 
     if len(ch) > 2: 
      average = sum(len(ch) for ch in sen)/len(sen) 
    print("Average word length:",average) 
    print() 

main() 

我已經得到了這麼多,但仍然無法找到一種方法來使單詞的平均字母數不包含少於2個字符的單詞!任何幫助,將不勝感激計算字符串中單詞的平均長度

+0

SUM(LEN(CH)在仙CH),讓你在仙所有單詞總和。 –

回答

0

for循環與此更換:

for ch in senstr.split(): 
    word_count = 0 
    letter_count = 0 
    if len(ch) > 2: 
     letter_count = letter_count + len(ch) 
     word_count = word_count + 1 
    print float(letter_count)/word_count