#!/usr/bin/python # -*- coding: UTF-8 -*- import re def NumberOfOccurencesOfWordInText(word,text): def NumberOfOccurencesOfWordInText(word,text): """Returns the nb. of occurences of whole word(s) (case insensitive) in a text""" #Basic attempt, does not pass all the tests: you have to improve it. # return text.lower().count(word.lower()) unformated = re.compile('\s+', flags=re.I|re.M|re.U) text_unformated = unformated.sub(' ', text.lower()) lword = word.lower() chaine_matcher = re.compile('(\W+'+lword+'\W+)|(\W+'+lword+'\Z)|(\A'+lword+'\W+)', flags=re.I|re.M|re.U) occurences = chaine_matcher.findall(text_unformated) return len(occurences)