Skip to content Skip to sidebar Skip to footer

Python Regex, Match Words In String And Get Count

I want to match a list of words with an string and get how many of the words are matched. Now I have this: import re words = ['red', 'blue'] exactMatch = re.compile(r'\b%s\b' % '\

Solution 1:

If you use findall instead of search, then you get a tuple as result containing all the matched words.

print exactMatch.findall("my blue cat")
print exactMatch.findall("my red car")
print exactMatch.findall("my red and blue monkey")
print exactMatch.findall("my yellow dog")

will result in

['blue'] ['red'] ['red', 'blue'] []

If you need to get the amount of matches you get them using len()

printlen(exactMatch.findall("my blue cat"))
printlen(exactMatch.findall("my red car"))
printlen(exactMatch.findall("my red and blue monkey"))
printlen(exactMatch.findall("my yellow dog"))

will result in

1 1 2 0

Solution 2:

If I got right the question, you only want to know the number of matches of blue or red in a sentence.

>>>exactMatch = re.compile(r'%s' % '|'.join(words), flags=re.IGNORECASE)>>>print exactMatch.findall("my blue blue cat")
['blue', 'blue']
>>>printlen(exactMatch.findall("my blue blue cat"))
2

You need more code if you want to test multiple colors

Solution 3:

Why not storing all words in a hash and iterate a lookup of every words in sentences thru a finditer

  words = { "red": 1 .... }
  word = re.compile(r'\b(\w+)\b')
  for i in word.finditer(sentence): 
     if words.get(i.group(1)):
       ....

Solution 4:

for w in words:
    if w in searchterm:
        print"found"

Post a Comment for "Python Regex, Match Words In String And Get Count"