0

Suppose I have this string

text = "microsoft,javascript java microsoft office"

If I want to count how many times microsoft office exists

print(text.count("microsoft office")) # returns 1

But if I want to count how many times java exists, without considering javascript

print(text.count("java")) # returns 2 but it should return 1

I taught of using split from re :

import re 
count = 0
text = "microsoft,javascript java microsoft office"
words = re.split("[ ,]", text)
for word in words:
    if word == "java":
        count += 1

print(count) # returns 1

It will work for java but not for microsoft office as it will split by space and the if condition will not be satisfied if word == "microsoft" if word == "office"

What I want is a way to mix count and split in such a way that can work for the two examples

Amine Messaoudi
  • 2,141
  • 2
  • 20
  • 37

1 Answers1

0

This can be done using findall operation in regex , try this code

import re
text = "microsoft,javascript java microsoft office"
word = input("enter a word to check its occurence ")
check = re.findall(word,text)
print(word +" occured "+str(len(check))+ " times")
Rajat
  • 118
  • 1
  • 5