How to perform t9 search, using python?

1.1k Views Asked by At

I have the code:

f = open("dict.txt", "r")
M = []
for line in f:
    l = line.split(" ")
    M.append(l)
print(M)
phone_letters = [
    ["a", "b", "c"],
    ["d", "e", "f"],
    ["g","h","i"],
    ["j","k","l"],
    ["m","n","o"],
    ["p","q","r","s"],
    ["t","u","v"],
    ["w","x","y","z"]
    ]
t = 0
k = 0
max = 100
for i in range(len(phone_letters)):
    for quantity in range(1, 20):
        if t == 1:  # > 9 - error7
            break
        if t == 2:
            break   # End of word
        if t == 4:
            break   #«MANUALLY».
        max = 100
        vvod_2 = int(input("Enter the next digit: "))
        if vvod_2 != 1:
            for i in range(len(phone_letters)):
                if (vvod_2 - 2) == i:
                    for i_2 in range(len(M)):
                        if len(M[i_2][0]) >= quantity:
                            if int(M[i_2][1][:-1]) < max:
                                for i_3 in range(len(phone_letters[i])):
                                    if M[i_2][0][(quantity - 1)] == phone_letters[i][i_3]:
                                        max = int(M[i_2][1][:-1])
                                        k = M[i_2][0][:quantity]
                                        t = 0
        quantity = quantity + 1
        print(k)
        if vvod_2 > 9:
            print("Error")
            t = 1
        if vvod_2 == 1:
            for i_last in range(len(M)):
                if str(k) == M[i_last][0]:
                    print("End of word.")
                    t = 2
                else:
                    t = 4

But this program doesn't work correct. I have the file "dict.txt", that looks like:

hello 27

play 32 

good 45

These numbers mean the probability of encountering the word. My program works, but it gives the results by every letter, not looking on the letters before.

For example, when we have: day 37 and after that we don't have another word, that starts with the same letter - after running the program by typing 3 - "d", typing again 3 - the result need to be "Manually", because my dictionary hasn't got a word, that starts on the same letter. The program above should find the word by the second letter in spite of the letters before. Help, please!

1

There are 1 best solutions below

0
On

I recently wrote such an algorithm as part of training. I hope it may be useful. It work with system dictionary, and you should import pathlib

DEFAULT_PATH_TO_WORDS_FILE = '/usr/share/dict/words'
PHONE_KEYS_CONFORMITY = {'2': 'abc',
                         '3': 'def',
                         '4': 'ghi',
                         '5': 'jkl',
                         '6': 'mno',
                         '7': 'pqrs',
                         '8': 'tuv',
                         '9': 'wxyz'}


def get_system_words(path_to_file: str) -> Tuple:
    with pathlib.Path(path_to_file).open(mode='r') as stream:
        file_content = stream.read()
    words_tuple = tuple(word.strip() for word in file_content.split('\n'))
    return words_tuple


def my_t9(input_numbers: str) -> List[str]:
    system_words = get_system_words(DEFAULT_PATH_TO_WORDS_FILE)
    filtered_system_words_by_len = tuple(filter(
        lambda word: len(word) == len(input_numbers),
        system_words))
    filtered_system_words_by_input = []
    for word in filtered_system_words_by_len:
        word_corresponds = True
        for index, letter in enumerate(word):
            if letter not in PHONE_KEYS_CONFORMITY[f'{input_numbers[index]}']:
                word_corresponds = False
                break
        if word_corresponds:
            filtered_system_words_by_input.append(word)
    return filtered_system_words_by_input