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

后端 未结 9 1649
甜味超标
甜味超标 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 11:53

    The concise version:

    average = lambda lst: sum(lst)/len(lst) #average = sum of numbers in list / count of numbers in list
    avg = average([len(word) for word in sentence.split()]) #generate a list of lengths of words, and calculate average
    

    The step-by-step version:

    def average(numbers):
        return sum(numbers)/len(numbers)
    sentence = input("Please enter a sentence: ")
    words = sentence.split()
    lengths = [len(word) for word in words]
    print 'Average length:', average(lengths)
    

    Output:

    >>> 
    Please enter a sentence: Hey, what's up?
    Average length: 4
    
    0 讨论(0)
  • 2021-01-03 11:54
    def main():
    
        sentence = input('Enter the sentence:  ')
        SumAccum = 0
        for ch in sentence.split():
            character = len(ch)
            SumAccum = SumAccum + character
    
        average = (SumAccum) / (len(sentence.split()))
        print(average)
    
    0 讨论(0)
  • 2021-01-03 12:01
    >>> sentence = "Hi my name is Bob"
    >>> words = sentence.split()
    >>> sum(map(len, words))/len(words)
    2.6
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-03 12:12
    s = input("Please enter a sentence: ")
    avg_word_len = len(s.replace(' ',''))/len(s.split())
    print('Word average =', avg_word_len)
    

    Output:

    Please enter a sentence: this is a testing string
    Word average = 4.0
    

    note: this is a plain vanilla use case, additional boundary conditions can be applied as required.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题