# Define a dictionary word_dict = [ 'us', 'often', 'there', 'have opinions', 'advice', 'differences'] The size of the sliding window # max_len = 5 # User input user_input = 'We often have differences of opinion' len(user_input) result: 9
Before implementing the maximum matching algorithm
# Before the maximum matching algorithm result = [] i = 0 while i < len(user_input): matched = False pos = i + max_len if i + max_len < len(user_input) else len(user_input) while user_input[i:pos] not in word_dict and i < pos: print(user_input[i:pos]) pos -= 1 if i < pos: matched = True result.append(user_input[i:pos]) i = pos if matched == True else i + max_len print(result)
Output:
We often have We often Us by There are often comments Often intentionally Often There are differences of opinion There are divided opinions [ 'We', 'often', 'have opinions', 'differences']
achieve the maximum matching algorithm after
After the maximum matching algorithm # result = [] i = len(user_input) while i > 0: matched = False pos = i - max_len if i - max_len > 0 else 0 while user_input[pos:i] not in word_dict and i > pos: print(user_input[pos:i]) pos += 1 if i > pos: matched = True result.insert(0, user_input[pos:i]) i = pos if matched == True else i - max_len print(result)
Output:
There are differences of opinion different opinions See differences There are often comments Often comments We often Often [ 'We', 'often', 'have opinions', 'differences']