![](/img/trans.png)
[英]Python: How can I calculate the average word length in a sentence using the .split command?
[英]i need to calculate average sentence length in python
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
"""
我想你正在尋找這樣的東西?
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 左右,代碼會有點不同。
我們可以使用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"))
盡管拆分過程是完全有條件的。
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())
我在這個答案中編輯了一些代碼,但它應該可以工作(我卸載了 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.