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

后端 未结 9 1683
甜味超标
甜味超标 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条回答
  •  梦毁少年i
    2021-01-03 12:17

    as a modular :

    import re
    
    def avg_word_len(s):
        words = s.split(' ') # presuming words split by ' '. be watchful about '.' and '?' below
        words = [re.sub(r'[^\w\s]','',w) for w in words] # re sub '[^\w\s]' to remove punctuations first
        return sum(len(w) for w in words)/float(len(words)) # then calculate the avg, dont forget to render answer as a float
    
    if __name__ == "__main__":
        s = raw_input("Enter a sentence")
        print avg_word_len(s)
    

提交回复
热议问题