In: Computer Science
Main Objective: Create a function collect_statistics to count the number of words and mean length of words in each sentence
This is my code so far but I am struggling to join the two functions together. I would appreciate the help!
The sentence given as an example is : "Haven't you eaten 8 oranges today?" the mean length of this sentence is 4.5 for reference.
Each sentence needs to be split up if given multiple sentences, assuming each sentence ends with a period.
Thank you!
My code so far:
def word_length_list(text):
text = text.replace('--',' ')
for p in string.punctuation + "‘’”“":
text = text.replace(p,'')
text = text.lower()
words = text.split()
word_length = []
for i in words:
count = 0
for j in i:
count = count + 1
word_length.append(count)
return(word_length)
testing1 = word_length_list("Haven't you eaten 8 oranges today?")
def collect_statistics(pandp):
for i in ["!","?"]:
if i in pandp:
pandp = pandp.replace(i,".")
pandp = pandp.split(".")
pandp = [sentence.split() for sentence in pandp]
pandp = [len(sentence) for sentence in pandp]
finalpandp = len(pandp)
return(finalpandp)
collect_statistics(testing1)
The code with removed error is given below.
The problem was in calling funtion collect_statistics. There parameter passed was testing1 which is not a string, rather the list of frequencies returned by the word_len_list. And we also needed to remove a few incorrect loops.
def word_length_list(text):
text = text.replace('--',' ')
for p in "‘’”“":
text = text.replace(p,'')
text = text.lower()
words = text.split()
word_length = []
for i in words:
count = 0
for j in i:
count = count + 1
word_length.append(count)
return(word_length)
testing1 = word_length_list("Haven't you eaten 8 oranges today?")
print(testing1)
def collect_statistics(pandp):
for i in ["!","?"]:
pandp = pandp.replace(i,".")
pandp = pandp.split(".")
pandp = [sentence.split() for sentence in pandp]
pandp = [len(sentence) for sentence in pandp]
finalpandp = len(pandp)
return(finalpandp)
res = collect_statistics("Haven't you eaten 8 oranges today?")
print(res)