First, your dictionary is the wrong way round, reverse it
dictionary = {'sunny': 'sun', 'banking': 'bank'}
a simple way to do it to avoid retyping it would be:
dictionary = {v:k for k,v in dictionary.items()}
note that if several words match a same word, reverting the dictionary won't work you have to solve the ambiguity first: so manually:
dictionary = {'sun', 'sunny': , 'sunn' : 'sunny', 'bank': 'banking'}
Then split and rebuild the string using a list comprehension and a get
access returning the original value if not in the dictionary
def stemmingWords(sentence,dictionary):
return " ".join([dictionary.get(w,w) for w in sentence.split()])
print(stemmingWords("the sun is shining",dictionary))
result:
the sunny is shining
note the deliberate ([])
when using join
. It's faster to pass explicitly the list comprehension than the generator in that case.