Reputation: 7403
new to python here. I am trying to write a program that calculate the average word length in a sentence and I have to do it using the .split command. btw im using python 3.2
this is what I've wrote so far
sentence = input("Please enter a sentence: ")
print(sentence.split())
So far i have the user enter a sentence and it successfully splits each individual word they enter, for example: Hi my name is Bob, it splits it into ['hi', 'my', 'name', 'is', 'bob']
but now I'm lost I dunno how to make it calculate each word and find the average length of the sentence.
Upvotes: 3
Views: 77923
Reputation: 1
text = input()
words=text.split()
single=''.join(words)
average=len(single)/len(words)
print(average)
Upvotes: 0
Reputation: 73
s = input("Please enter a sentence: ")
avg_word_len = len(s.replace(' ',''))/len(s.split())
print('Word average =', avg_word_len)
Output:
Please enter a sentence: this is a testing string
Word average = 4.0
note: this is a plain vanilla use case, additional boundary conditions can be applied as required.
Upvotes: 0
Reputation: 1
def average():
value = input("Enter the sentence:")
sum = 0
storage = 0
average = 0
for i in range (len(value)):
sum = sum + 1
storage = sum
average = average+storage
print (f"the average is :{average/len(value)}")
return average/len(value)
average()
Upvotes: -1
Reputation: 765
as a modular :
import re
def avg_word_len(s):
words = s.split(' ') # presuming words split by ' '. be watchful about '.' and '?' below
words = [re.sub(r'[^\w\s]','',w) for w in words] # re sub '[^\w\s]' to remove punctuations first
return sum(len(w) for w in words)/float(len(words)) # then calculate the avg, dont forget to render answer as a float
if __name__ == "__main__":
s = raw_input("Enter a sentence")
print avg_word_len(s)
Upvotes: 0
Reputation: 336488
In Python 3 (which you appear to be using):
>>> sentence = "Hi my name is Bob"
>>> words = sentence.split()
>>> average = sum(len(word) for word in words) / len(words)
>>> average
2.6
Upvotes: 23
Reputation: 109
def averageWordLength(mystring):
tempcount = 0
count = 1
wordcount = 0
try:
for character in mystring:
if character == " ":
tempcount +=1
if tempcount ==1:
count +=1
else:
tempcount = 0
try:
if character.isalpha(): #sorry for using the .isalpha
wordcount += 1
except:
wordcount = wordcount + 0
if mystring[0] == " " or mystring.endswith(" "): #i'm sorry for using the .endswith
count -=1
try:
result = wordcount/count
if result == 0:
result = "No words"
return result
else:
return result
except ZeroDivisionError:
error = "No words"
return error
except Exception:
error = "Not a string"
return error
mystring = "What big spaces you have!" output is 3.0 and I didn't use the split
Upvotes: 0
Reputation: 29
def main():
sentence = input('Enter the sentence: ')
SumAccum = 0
for ch in sentence.split():
character = len(ch)
SumAccum = SumAccum + character
average = (SumAccum) / (len(sentence.split()))
print(average)
Upvotes: 0
Reputation: 172437
You might want to filter out punctuation as well as zero-length words.
>>> sentence = input("Please enter a sentence: ")
Filter out punctuation that doesn't count. You can add more to the string of punctuation if you want:
>>> filtered = ''.join(filter(lambda x: x not in '".,;!-', sentence))
Split into words, and remove words that are zero length:
>>> words = [word for word in filtered.split() if word]
And calculate:
>>> avg = sum(map(len, words))/len(words)
>>> print(avg)
3.923076923076923
Upvotes: 8
Reputation: 10526
The concise version:
average = lambda lst: sum(lst)/len(lst) #average = sum of numbers in list / count of numbers in list
avg = average([len(word) for word in sentence.split()]) #generate a list of lengths of words, and calculate average
The step-by-step version:
def average(numbers):
return sum(numbers)/len(numbers)
sentence = input("Please enter a sentence: ")
words = sentence.split()
lengths = [len(word) for word in words]
print 'Average length:', average(lengths)
Output:
>>>
Please enter a sentence: Hey, what's up?
Average length: 4
Upvotes: 1
Reputation: 304493
>>> sentence = "Hi my name is Bob"
>>> words = sentence.split()
>>> sum(map(len, words))/len(words)
2.6
Upvotes: 5