You need to check all neighbor permutations from 1 (each individual word) to len (text) (entire line). You can generate neighboring permutations as follows:
text = 'I have a smartphone and a Smart TV' array = text.lower().split() key_permutations = [" ".join(array[j:j + i]) for i in range(1, len(array) + 1) for j in range(0, len(array) - (i - 1))] >>> key_permutations ['i', 'have', 'a', 'smartphone', 'and', 'a', 'smart', 'tv', 'i have', 'have a', 'a smartphone', 'smartphone and', 'and a', 'a smart', 'smart tv', 'i have a', 'have a smartphone', 'a smartphone and', 'smartphone and a', 'and a smart', 'a smart tv', 'i have a smartphone', 'have a smartphone and', 'a smartphone and a', 'smartphone and a smart', 'and a smart tv', 'i have a smartphone and', 'have a smartphone and a', 'a smartphone and a smart', 'smartphone and a smart tv', 'i have a smartphone and a', 'have a smartphone and a smart', 'a smartphone and a smart tv', 'i have a smartphone and a smart', 'have a smartphone and a smart tv', 'i have a smartphone and a smart tv']
Now we are replacing the dictionary:
import re for permutation in key_permutations: if permutation in dict: text = re.sub(re.escape(permutation), dict[permutation], text, flags=re.IGNORECASE) >>> text 'I have a toy and a junk'
Although you most likely want to try rearranging in the reverse order, the longest ones first, so more specific phrases take precedence over individual words.