我需要计算python中的平均句子长度

时间:2014-12-30 07:47:17

标签: python python-3.x

avg_sentence_length是计算句子平均长度的函数

def avg_sentence_length(text):
    """ (list of str) -> float

    Precondition: text contains at least one sentence.

    A sentence is defined as a non-empty string of non-terminating 
    punctuation surrounded by terminating punctuation or beginning or 
    end of file. Terminating punctuation is defined as !?.

    Return the average number of words per sentence in text.   

    >>> text = ['The time has come, the Walrus said\n',
         'To talk of many things: of shoes - and ships - and sealing wax,\n',
         'Of cabbages; and kings.\n',
         'And why the sea is boiling hot;\n',
         'and whether pigs have wings.\n']
    >>> avg_sentence_length(text)
    17.5
    """

3 个答案:

答案 0 :(得分:0)

我认为你在找这样的东西?

def averageSentence(sentence):
    words = sentence.split()
    average = sum(len(word) for word in words)/len(words)
    print(average)

def main():
    sentence = input("Enter Sentence: ")
    averageSentence(sentence)
main()

output:
Enter Sentence: my name is something
4.25

我使用空闲3及以上。如果你正在使用python 2.7左右,那么代码会有所不同。

答案 1 :(得分:0)

我们可以使用 reduce 和 lambda。

from functools import reduce

def Average(l): 
    avg = reduce(lambda x, y: x + y, l) / len(l)
    return(avg)

def AVG_SENT_LNTH(File):
    
    SENTS = [i.split() for i in open(File).read().splitlines()]
    Lengths = [len(i) for i in SENTS]
    return(Average(Lengths))


print("Train\t", AVG_SENT_LNTH("Train.dat"))

虽然拆分过程是完全有条件的。

答案 2 :(得分:-3)

我已经在这个答案中编了一些代码,但它应该工作(我卸载了Python,所以我无法测试抱歉。(这是为了在这个垃圾笔记本电脑上留出空间,只开始于28GB!))这是代码:

def findAverageSentenceLength(long1, medium2, short3):
    S1LENGTH = long1.length
    S2LENGTH = medium2.length
    S3LENGTH = short3.length

    ADDED_LENGTHS = S1LENGTH + S2LENGTH + S3lENGTH
    AVERAGE = ADDED_LENGTHS / 3

    print("The average sentence length is", AVERAGE, "!")
long1input = input("Enter a 17-30 word sentence.")
medium2input = input("Enter a 10-16 word sentence.")
short3input = input("Enter a 5-9 word sentence.")

findAverageSentenceLength(long1input, medium2input, short3input)

希望这有帮助。

PS:这只适用于Python 3