Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I calculate the number of times a word occurs in a sentence?

So I've been learning Python for some months now and was wondering how I would go about writing a function that will count the number of times a word occurs in a sentence. I would appreciate if someone could please give me a step-by-step method for doing this.

like image 310
qzxt Avatar asked Nov 25 '11 17:11

qzxt


2 Answers

text=input("Enter your sentence:")
print("'the' appears", text.count("the"),"times")

simplest way to do it

like image 144
beth Avatar answered Oct 08 '22 20:10

beth


Simplest way:

def count_occurrences(word, sentence):
    return sentence.count(word)
like image 45
ekocibar Avatar answered Oct 08 '22 19:10

ekocibar