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"
    p = raw_input("Enter a sentence: ")
    words = string.split(p)
    wordCount = string.count(words, p)
    print "The total word count is:", wordCount

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.


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

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!

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

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

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).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.