Pewtas
Pewtas

Reputation: 53

count number of occurencecs of string in text NOT substring

probably a pretty simple solution but I just can't find a google answer because the moment you type sub-string in google search i get bombarded with wrong answers i don't need

I have a string: text = "Hello, how are you doing doing howhow abhowab"

I would like to count the number of occurrences of "how" (1) NOT the amount of occurrences of the sub-string "how" (4).

Thank you for your help :)

Upvotes: 0

Views: 402

Answers (4)

Ajay
Ajay

Reputation: 5347

text = "Hello, how are you doing doing howhow abhowab"
from collections import Counter
Counter(text.split(' '))['how']
2

Counter is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts

Another way of doins is using operator

import operator
operator.countOf("Hello, how are you doing doing howhow abhowab how".split(' '),"how")
2

Upvotes: 0

ph140
ph140

Reputation: 475

If you want it to only detect 'how' and not 'howhow' you could look for the substring ' how '

text = "Hello, how are you doing doing howhow abhowab"
print(text.count(' how '))

Upvotes: -1

Donal
Donal

Reputation: 32713

text = "Hello, how are you doing doing howhow abhowab"
    
word = "how"

#split the text into an array of words
wordlist = text.split()
    
#print out the number of occurrences of the word
print(wordlist.count(word))

Upvotes: 1

azro
azro

Reputation: 54148

Use a regex with \b which means word boundary

import re

sentence = "Hello, how are you doing doing howhow abhowab"
word = "how"
nb_matches = len(re.findall(rf"\b{word}\b", sentence))
print(nb_matches)  # 1

You can also split the sentence in words, then count

nb_matches = sentence.split().count(word)
print(nb_matches)  # 1

Upvotes: 3

Related Questions