Whinly1987
Whinly1987

Reputation: 41

Simple translator using dict, Python?

I'm using dict to store a text file with English word first then Spanish word second in columns.

What I want it to do is be able to search a word(English word) and then translate it to Spanish. I'm not sure why this is returning None every time I enter a word to translate.

Im using python3, if that makes a difference.

def getDict():
    myDict  = {}

    for line in open("eng2sp.txt"):
       for n in line:
           (eng,span) = line.split()
           myDict[eng] = span


    print("Translate from English to Spanish")
    word = input("Enter the english word to translate:")

    print(search(myDict,word))



def search(myDict,lookup):
    for key, value in myDict.items():
        for v in value:
            if lookup in v:
                return



def main():
    getDict()


main()

Output:

enter image description here

Upvotes: 3

Views: 1821

Answers (2)

Steve Misuta
Steve Misuta

Reputation: 1033

The search function is really not needed. You can find the translation directly by accessing my_dict[word].

Assuming your text file has entries like:

hello hola
goodbye adios

then you can use something like this:

my_dict = {}

with open('eng2sp.txt','r') as f:
    for line in f.readlines():
        eng, span = line.split()
        my_dict[eng] = span


while True:
    word = input('\nEnter english word to translate: ')
    if word == "":
        break
    elif word in my_dict.keys():
        print(my_dict[word])
    else:
        print('Error: word not in dictionary')

Upvotes: 2

Galax
Galax

Reputation: 1431

This could be much simpler:

def search(myDict,lookup):
    if lookup in myDict:
        return myDict[lookup]
    return "NOT FOUND"

This code will give much better performance for large dictionaries. You might want to return None instead of a string when the item isn't found, depends how you want to handle that case.

Upvotes: 4

Related Questions