Python: How can I calculate the average word length in a sentence using the .split command?

后端 未结 9 1646
甜味超标
甜味超标 2021-01-03 11:40

new to python here. I am trying to write a program that calculate the average word length in a sentence and I have to do it using the .split command. btw im using python 3.2

9条回答
  •  孤街浪徒
    2021-01-03 12:05

    You might want to filter out punctuation as well as zero-length words.

    >>> sentence = input("Please enter a sentence: ")
    

    Filter out punctuation that doesn't count. You can add more to the string of punctuation if you want:

    >>> filtered = ''.join(filter(lambda x: x not in '".,;!-', sentence))
    

    Split into words, and remove words that are zero length:

    >>> words = [word for word in filtered.split() if word]
    

    And calculate:

    >>> avg = sum(map(len, words))/len(words)
    >>> print(avg) 
    3.923076923076923
    

提交回复
热议问题