954,549 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Word Count Issues

I have another string dilemma. I am asked to write a program that counts the number of words in a sentence entered by the user. This is what I have right now, although I don't think that it is anywhere near being correct:

import string
def main():
    print "This program calculates the number of words in a sentence"
    print
    p = raw_input("Enter a sentence: ")
    words = string.split(p)
    wordCount = string.count(words, p)
    print "The total word count is:", wordCount
main()

I'm pretty sure that the string.count() is all wrong but I don't understand what I'm supposed to put in the parentheses. Assistance would be greatly appreciated. Thank you.

pyguy25
Newbie Poster
10 posts since Mar 2007
Reputation Points: 10
Solved Threads: 0
 

Hi!

Well, you did it ... nearly :)

words = string.split(p)

Ok,words is now a list, and it's elements are the words in the sentence. You want to know how many words there are in the sentence ... so ... how do you get the number of elements in a list? (hint: len() is your friend).
Got it?

EDIT: Strings have their own split() method. You don't need the string-module here.

Regards, mawe

mawe
Junior Poster
133 posts since Sep 2005
Reputation Points: 19
Solved Threads: 58
 

Wow! It was a lot simpler than I thought. I just had to change wordCount = string.count() to wordCount = len(words) . Thank you so much!

pyguy25
Newbie Poster
10 posts since Mar 2007
Reputation Points: 10
Solved Threads: 0
 

Would there be a way for me to modify this program to calculate the average word length in a sentence?

pyguy25
Newbie Poster
10 posts since Mar 2007
Reputation Points: 10
Solved Threads: 0
 

Actually, never mind that last question. I think I've got it now.

pyguy25
Newbie Poster
10 posts since Mar 2007
Reputation Points: 10
Solved Threads: 0
 
Would there be a way for me to modify this program to calculate the average word length in a sentence?

http://www.daniweb.com/techtalkforums/thread72136.html

go through this link...


regards,
kath.

katharnakh
Posting Whiz in Training
237 posts since Jan 2006
Reputation Points: 19
Solved Threads: 34
 

There may some issues with my solution if you have some funky grammar going on, but

numOfWords = (yourSentenceString.count(' ')+1)


worked fine for me and it's a bit more succinct. Only two lines of code (the first being when you assign your sentence string).

j6m8
Newbie Poster
3 posts since Jul 2010
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You