3

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

这是我到目前为止写的

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

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

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

4

9 回答 9

22

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

>>> sentence = "Hi my name is Bob"
>>> words = sentence.split()
>>> average = sum(len(word) for word in words) / len(words)
>>> average
2.6
于 2012-10-06T16:30:05.573 回答
8

您可能想要过滤掉标点符号以及零长度的单词。

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

过滤掉不重要的标点符号。如果需要,您可以在标点字符串中添加更多内容:

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

拆分成单词,并删除长度为零的单词:

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

并计算:

>>> avg = sum(map(len, words))/len(words)
>>> print(avg) 
3.923076923076923
于 2012-10-06T16:54:47.687 回答
4
>>> sentence = "Hi my name is Bob"
>>> words = sentence.split()
>>> sum(map(len, words))/len(words)
2.6
于 2012-10-06T16:40:13.067 回答
1

简洁版:

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

分步版本:

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)

输出:

>>> 
Please enter a sentence: Hey, what's up?
Average length: 4
于 2012-10-06T16:31:18.347 回答
0
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)
于 2014-07-21T22:33:38.460 回答
0
s = input("Please enter a sentence: ")
avg_word_len = len(s.replace(' ',''))/len(s.split())
print('Word average =', avg_word_len)

输出:

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

注意:这是一个普通的用例,可以根据需要应用额外的边界条件。

于 2020-10-09T05:24:46.127 回答
0

作为模块化:

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)
于 2019-10-08T06:42:48.063 回答
0
  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 = "你有多大的空间!" 输出为 3.0,我没有使用拆分

于 2017-05-31T17:50:46.323 回答
-1
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()
于 2020-04-28T20:59:12.513 回答