[英]i need to calculate average sentence length in python
avg_sentence_length
is function which calculate average length of a sentence 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
"""
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.我正在使用空闲 3 及更高版本。 If you are working with python 2.7 or so, the code will be a little bit different.
如果你使用 python 2.7 左右,代码会有点不同。
We can use reduce and lambda.我们可以使用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"))
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:我在这个答案中编辑了一些代码,但它应该可以工作(我卸载了 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)
Hope this helps.希望这可以帮助。
PS: This WILL only work in Python 3 PS:这只适用于 Python 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.