计算字符串

时间:2016-02-23 03:35:31

标签: python-3.x

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个字符的单词!任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

用以下方法替换循环:

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