Python:如何使用 .split 命令计算句子中的平均词长?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12761510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:49:07  来源:igfitidea点击:

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

pythonpython-3.x

提问by Average kid

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

这里是python的新手。我正在尝试编写一个程序来计算一个句子中的平均词长,我必须使用 .split 命令来完成它。顺便说一句,我使用的是 python 3.2

this is what I've wrote so far

这是我到目前为止所写的

sentence = input("Please enter a sentence: ")
print(sentence.split())

So far i have the user enter a sentence and it successfully splits each individual word they enter, for example: Hi my name is Bob, it splits it into ['hi', 'my', 'name', 'is', 'bob']

到目前为止,我让用户输入了一个句子,它成功地拆分了他们输入的每个单词,例如:嗨,我的名字是鲍勃,它将其拆分为 ['hi', 'my', 'name', 'is', '鲍勃']

but now I'm lost I dunno how to make it calculate each word and find the average length of the sentence.

但现在我迷路了,我不知道如何让它计算每个单词并找到句子的平均长度。

采纳答案by Tim Pietzcker

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

在 Python 3(您似乎正在使用)中:

>>> sentence = "Hi my name is Bob"
>>> words = sentence.split()
>>> average = sum(len(word) for word in words) / len(words)
>>> average
2.6

回答by Anuj Gupta

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

回答by John La Rooy

>>> sentence = "Hi my name is Bob"
>>> words = sentence.split()
>>> sum(map(len, words))/len(words)
2.6

回答by Lennart Regebro

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

回答by Abdulahi Abdinur

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)

回答by Darrell White

  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

mystring = "你有多大的空间!" 输出是 3.0,我没有使用拆分

回答by khanna

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)

回答by jeffrey

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()