5
\$\begingroup\$

Function : User enters a word in korean and the program translates (defines) it in english.

What improvements can I make?

Extra : What other challenges would you recommend that incorporates both JSON and python?

KoreanDictionary.py

import json
from difflib import get_close_matches

korean_data = json.load(open("korean_vocabulary.json"))

def my_translator(word):
    if word in korean_data.keys():
        return korean_data[word]
    elif len(get_close_matches(word,korean_data.keys(),n=1,cutoff=.69)) > 0:
        word = get_close_matches(word,korean_data.keys(),n=1,cutoff=.69)[0]
        return korean_data[word]
    else:
        return "Word does not exist."



if __name__ == '__main__':

    user_input = input("Define:")
    definition = str(my_translator(user_input)).replace('[','').replace(']','').replace("'",'')
    print(user_input + ": " + definition)

korean_vocabulary.json

{"안녕하세요": ["hello"],"죽어버려": ["GO DIE"],"상황": ["situation"],"어려워": ["hard; difficult"],
    "모르겠다": ["I don't know."],"조건": ["condition"],"정규직 직업": ["full-time job"],
    "탈락": ["eliminate; out"], "눈치": ["quick to catch; tactfulness"],"슬픈": ["sad"],
    "복잡한": ["complicated"],"완전": ["completely"],"반대": ["opposite"],"대박": ["jackpot; awesome"],
    "어꺠": ["shoulders"],"얼굴": ["face"]}
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$
if word in korean_data.keys():
    return korean_data[word]

This is better written as:

trans = korean_data.get(word)
if trans:
    return trans

This:

elif len(get_close_matches(word,korean_data.keys(),n=1,cutoff=.69)) > 0:
    word = get_close_matches(word,korean_data.keys(),n=1,cutoff=.69)[0]
    return korean_data[word]

calls for a few changes. Firstly, you don't need an elif, simply an if - because the previous block returned. Also, you should avoid re-issuing that entire get_close_matches call, and instead write a temporary variable:

words = get_close_matches(word,korean_data.keys(),n=1,cutoff=.69)
if words:
    return korean_data[words[0]]

This:

return "Word does not exist."

is not really good practice. It's "in-band error information", i.e. you're mixing valid data with an error message. Instead, you should be raise-ing an exception, catching it in your calling code, and outputting an error message there.

What other challenges would you recommend that incorporates both JSON and python?

Download or scrape a real Korean-English dictionary dataset, either incorporating it into your application or setting up a REST client to contact a translation server somewhere. If local, save it as a format more efficient than JSON - perhaps compressed pickle, or SQLite. There are many ways to store a local database, and each has its advantages and disadvantages, but that's a topic for another question.

\$\endgroup\$
9
  • \$\begingroup\$ I would never recommend to use pickle, especially to someone not so experienced with it, it makes code vulnerable & dictionary file hardly manageable, can't see any pros in doing that, maybe using some sort of database (SQLite for beginning) can be a better idea \$\endgroup\$ Dec 25, 2018 at 5:56
  • \$\begingroup\$ @AzatIbrakov It's only one of many alternatives, and it is appropriate for some cases (otherwise, why would it be included in Python?) \$\endgroup\$
    – Reinderien
    Dec 25, 2018 at 17:13
  • \$\begingroup\$ it is used internally, mainly in multiprocessing stdlib module, even docs warns us that pickle is not secure \$\endgroup\$ Dec 25, 2018 at 17:15
  • \$\begingroup\$ It's not secure against maliciously constructed data. In this use case (a translation dictionary), the data are not being supplied by the user, so the risk is lower. \$\endgroup\$
    – Reinderien
    Dec 25, 2018 at 17:17
  • 2
    \$\begingroup\$ An example why in-band error information is bad: boingboing.net/2008/07/15/chinese-restaurant-c.html \$\endgroup\$
    – Graipher
    Dec 25, 2018 at 20:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.