from collections import defaultdict def isalnum_without_apostroph(ch: str): return ch.isalnum() and ch != "'" def count_words(sentance: str) -> dict: sent_list = list(sentance) words = defaultdict(int) for i, ch in enumerate(sent_list): if(ch == "'"): if((isalnum_without_apostroph(sent_list[max(i-1, 0)])) and (isalnum_without_apostroph(sent_list[min(i+1, len(sent_list)-1)]))): pass else: sent_list[i] = " " elif(not ch.isalnum()): sent_list[i] = " " for w in ''.join(sent_list).lower().split(" "): if not len(w): continue words[w] += 1 return dict(words)