Regular expressions - counting how many times a word appears in a text

Viewed 512

What I am trying to set up is a function that given a certain text will print out the number of times the words ['color', 'Colour', 'Color','Colour']appear. So that I get the following result:

assert colorcount("Color Purple") == 1

assert colorcount("Your colour is better than my colour") == 2

assert colorcount("color Color colour Colour") == 4

What I have is

import re

def colorcount(text):

all_matches = re.findall('color', 'Colour', 'Color'. 'Colour', text)

return len(all_matches)

print(colorcount(text)

It doesn't work so how can I write the code to make it work as I want it to?

4 Answers

If you wanted to use regular expressions, you could go for something like this:

import re

def colorcount(text):
  r = re.compile(r'\bcolour\b | \bcolor\b', flags = re.I | re.X)
  count = len(r.findall(text))
  print(count)
  return count

# These asserts work as expected without raising an AssertionError.
assert colorcount("Color Purple") == 1
assert colorcount("Your colour is better than my colour") == 2
assert colorcount("color Color colour Colour") == 4

Which outputs:

1
2
4

You can simply convert text to specific case (i.e. all lower) and then use string's count() to loop each occurrence of a keyword:

def colorcount(text):
    KEY_WORDS = [ 'color', 'colour' ]
    counter = 0
    sanitexed_text = text.lower()
    for kw in KEY_WORDS:
        counter += sanitexed_text.count(kw.lower())
    return counter

text = 'color ds das Colour dsafasft e re Color'

# 3
print(colorcount(text))

# All following asserts pass
assert colorcount("Color Purple") == 1
assert colorcount("Your colour is better than my colour") == 2
assert colorcount("color Color colour Colour") == 4

Try this

def colorcount(text):
    return len(re.findall('[c|C]olou{0,1}r', text))

assert colorcount("Color Purple") == 1
assert colorcount("Your colour is better than my colour") == 2
assert colorcount("color Color colour Colour") == 4

Use the following regex with flags re.I (case insensitivity) and re.findll and then return the length of the returned list:

\bcolou?r\b
import re

def colorcount(text):
  return len(re.findall(r'\bcolou?r\b', text, flags=re.I))

print(colorcount('color Color colour Colour'))

Prints:

4

Related