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

后端 未结 9 1645
甜味超标
甜味超标 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:19

    In Python 3 (which you appear to be using):

    >>> sentence = "Hi my name is Bob"
    >>> words = sentence.split()
    >>> average = sum(len(word) for word in words) / len(words)
    >>> average
    2.6
    
    0 讨论(0)
  • 2021-01-03 12:20
      def averageWordLength(mystring):
    tempcount = 0
    count = 1
    
    wordcount = 0
    try:
        for character in mystring:
            if character == " ":
                tempcount +=1
                if tempcount ==1:
                    count +=1
    
            else:
                tempcount = 0
                try:
                    if character.isalpha(): #sorry for using the .isalpha
                        wordcount += 1
                except:
                    wordcount = wordcount + 0
        if mystring[0] == " " or mystring.endswith(" "): #i'm sorry for using the .endswith
                count -=1
    
        try:
            result = wordcount/count
            if result == 0:
                result = "No words"
                return result
            else:
                return result
    
        except ZeroDivisionError:
            error = "No words"
            return error
    
    except Exception:
        error = "Not a string"
        return error
    

    mystring = "What big spaces you have!" output is 3.0 and I didn't use the split

    0 讨论(0)
  • 2021-01-03 12:20
    def average():
        value = input("Enter the sentence:")
        sum = 0
        storage = 0
        average = 0
    
        for i in range (len(value)):
            sum = sum + 1
            storage = sum
            average = average+storage
    
        print (f"the average is :{average/len(value)}")
    
        return average/len(value)
    
    average()
    
    0 讨论(0)
提交回复
热议问题