简体   繁体   中英

i need to calculate average sentence length in python

avg_sentence_length is function which calculate average length of a sentence

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
    """

I think you are looking for something like this?

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

I am using idle 3 and above. If you are working with python 2.7 or so, the code will be a little bit different.

We can use reduce and 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"))

Though the splitting process is totally conditional.

import doctest
import re


def avg_sentence_length(text):
    r"""(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
    """
    terminating_punct = "[!?.]"
    punct = r"\W"  # non-word characters
    sentences = [
        s.strip()  # without trailing whitespace
        for s in re.split(
            terminating_punct,
            "".join(text).replace("\n", " "),  # text as 1 string
        )
        if s.strip()  # non-empty
    ]

    def wordcount(s):
        """Split sentence s on punctuation
        and return number of non-empty words
        """
        return len([w for w in re.split(punct, s) if w])

    return sum(map(wordcount, sentences)) / len(sentences)


# test the spec. I just made the docstring raw with 'r'
# and added ... where needed
doctest.run_docstring_examples(avg_sentence_length, globals())

I have edited the code a bit in this answer but it should work (I uninstalled Python so I can't test sorry. (It was to make space on this rubbish laptop that only started with 28GB!) ) This is the code:

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)

Hope this helps.

PS: This WILL only work in Python 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM