| | |
Average Word Length
Thread Solved |
•
•
Join Date: Mar 2007
Posts: 10
Reputation:
Solved Threads: 0
This is a modified program from the word count program that I posted about. I am trying to calculate the average word length in a sentence. Here is my code so far:
I keep getting an error like 'list' object has no attribute 'split'.
Python Syntax (Toggle Plain Text)
def main(): print "This program will calculate the average word length in a sentence" s = raw_input("Enter a sentence: ") words = string.split(s) wordCount = len(words) ch = string.split(words) charCount = len(ch) avgLength = charCount / wordCount print "The average word length of the sentence '", s,"', is", avgLength,"words." main()
Last edited by pyguy25; Mar 11th, 2007 at 12:23 pm.
I am a little confused with the 'string.split(s)' I thought it was more like s.split():
Are there different versions of Python floating about?
Python Syntax (Toggle Plain Text)
s = "Just a test string" words = s.split() print words
•
•
Join Date: Sep 2005
Posts: 133
Reputation:
Solved Threads: 58
•
•
•
•
I keep getting an error like 'list' object has no attribute 'split'.
Python Syntax (Toggle Plain Text)
words = string.split(s)
Python Syntax (Toggle Plain Text)
ch = string.split(words)

Here is a receipe how to find the average word-length:
1. Split the string into words (hint: We have that already
)2. Do something like
total = 0. We need this later3. Iterate over the words in the list. (hint:
for word in words:)4. Find the length of the current word (hint: a word is just a list of characters
)5. Add this length to total.
6. Ok, after we've done this with every word, total is the sum of the wordlengths.
7. Divide total by the number of words.
8. That's it.
•
•
Join Date: Mar 2007
Posts: 10
Reputation:
Solved Threads: 0
ok, got it:
Python Syntax (Toggle Plain Text)
def main(): print "This program will calculate the average word length in a sentence" s = raw_input("Enter a sentence: ") words = string.split(s) wordCount = len(words) sum = 0 for word in words: ch = len(word) sum = sum + ch avg = sum / wordCount if avg is 1: print "In the sentence '", s,"', the average word length is", avg,"letter." else: print "In the sentence '", s,"', the average word length is", avg,"letters." main()
•
•
Join Date: Sep 2005
Posts: 133
Reputation:
Solved Threads: 58
•
•
•
•
Okay, I'll try that. Sorry, I'm a beginner at Python so I might ask stupid or obvious questions. Just bare with me. It'll come easier to me eventually.
Your questions are absolutely not stupid, and before you ask you try to find a solution by yourself. That's more than some others here do.
Ok, just one comment on your code:
Python Syntax (Toggle Plain Text)
sum = 0
Here's a shorter version of your code(using sum):
Python Syntax (Toggle Plain Text)
s = "This is a short sentence" l = s.split() print sum( [ len(word) for word in l ] ) / len(l)
Regards, mawe
•
•
Join Date: Jul 2006
Posts: 608
Reputation:
Solved Threads: 150
Good job! Just to make your code robust, you should check for dividing by zero:
If you want to continue to improve the code beyond that, you might consider turning the average word count into a separate function, so that it could be used by other programs for any old purpose. Doing so would have the positive side effect of cleaning up your code.
In general, it's usually better to have lots of small functions that do one thing rather than a few number of large functions that do lots of things. Your main() interacts with the user, finds the average, and prints the results ... a bit too Swiss-army-knifish for my taste.
Also, you might consider reading the Python docs tutorial on list generators. A list generator can simplfiy your code like this:
That one line replaces the entire sum=0 and for-loop section.
Jeff
Python Syntax (Toggle Plain Text)
if wordCount != 0: avg = sum / wordCount else: avg = 0
If you want to continue to improve the code beyond that, you might consider turning the average word count into a separate function, so that it could be used by other programs for any old purpose. Doing so would have the positive side effect of cleaning up your code.
In general, it's usually better to have lots of small functions that do one thing rather than a few number of large functions that do lots of things. Your main() interacts with the user, finds the average, and prints the results ... a bit too Swiss-army-knifish for my taste.

Also, you might consider reading the Python docs tutorial on list generators. A list generator can simplfiy your code like this:
Python Syntax (Toggle Plain Text)
total = sum([len(word) for word in words]
That one line replaces the entire sum=0 and for-loop section.
Jeff
•
•
Join Date: Apr 2006
Posts: 148
Reputation:
Solved Threads: 40
split will break if your input have punctuations. eg word.Test . This will be counted as 1?
(although a blank space comes after a full stop.)
anyway, here's another way to do it,
(although a blank space comes after a full stop.)
anyway, here's another way to do it,
Python Syntax (Toggle Plain Text)
>>> import re >>> s = "This program will calculate the average word length in a sentence.Tehas dfsdskj 323 5543" >>> len(re.findall("\w+",s)) 15
![]() |
Similar Threads
- Word Count Issues (Python)
- Sorting lists by word length: How do I do it? (Python)
- Help! Errors in program (average characters) (C++)
Other Threads in the Python Forum
- Previous Thread: Assure n is a number
- Next Thread: Word Count Issues
| Thread Tools | Search this Thread |
abrupt alarm ansi anti approximation assignment avogadro backend beginner binary bluetooth calculator character cmd code customdialog cx-freeze data decimals dictionaries dictionary directory dynamic error examples exe file float format function gnu graphics gui halp heads homework http ideas import input java launcher leftmouse line linux list lists loop module mouse number numbers output parsing path pointer port prime programming progressbar projects push py2exe pygame pyglet pyqt python random recursion schedule screensaverloopinactive script scrolledtext sqlite statistics string strings sudokusolver sum table terminal text thread threading time tlapse tricks tuple tutorial twoup ubuntu unicode urllib urllib2 variable ventrilo wikipedia write wxpython xlib






