Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 611
Whinly1987 Avatar asked Sep 15 '26 18:09

Whinly1987


1 Answers

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.

like image 167
Galax Avatar answered Sep 17 '26 07:09

Galax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!