0

I was wondering how, in python, I could count the occurrences of the word "the" in a string. The problem I get is that it will count "the" in words like: there, theatre....etc

s = "The Journey: today I went there! There was not the...theatre but the Walgreens so I could buy a thermometer"

howmanythe = s.count("the") #I feel like here you could do " the " but I would miss any "the" after grammar notation
print("There are {} many the's in that phrase".format(howmanythe))

Sorry if my formating is bad, this is my first post.

J_Steak
  • 11
  • 1

1 Answers1

2

You may try a regex search on \bthe\b, in case insensitive mode, which will find all the words in the text:

s = "The Journey: today I went there! There was not the...theatre but the Walgreens so I could buy a thermometer"
num = len(re.findall(r'\bthe\b', s, flags=re.IGNORECASE))
print("There were " + str(num) + " 'the' words in the text")

This prints:

There were 3 'the' words in the text
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360