将variable转换为JSON:

JSON will allow us to save this object to a JSON file, and then reconstitute it later. To get an idea for what JSON format looks like we can use dumps which dumps a variable to a JSON string:

import json

In [6]: json.dumps(eng_chn_dict)
Out[6]: '{"television": ["\\u7535\\u89c6", ""], "apple": ["\\u82f9\\u679c", ""], "thank you": ["\\u8c22\\u8c22", "\\u8c22\\u8c22\\u4f60"], "computer": ["\\u7535\\u8111", ""], "goodbye": ["\\u518d\\u89c1", ""], "English": ["\\u4e2d\\u6587", ""], "hello": ["\\u4f60\\u597d", ""]}'

Now, let's save our dictionary object to a JSON file. Note that when opening a file for writing, we open it with the 'w' code (instead of 'r'):

In [7]: f = open('chinese.json','w')
In [8]: json.dump(eng_chn_dict, f)
In [9]: f.close()

Read JSON

In [1]: import json
In [2]: f = open('chinese.json','r')

In [3]: new_dict = json.load(f)

In [4]: new_dict
Out[4]: 
{u'English': [u'\u4e2d\u6587', u''],
 u'apple': [u'\u82f9\u679c', u''],
 u'computer': [u'\u7535\u8111', u''],
 u'goodbye': [u'\u518d\u89c1', u''],
 u'hello': [u'\u4f60\u597d', u''],
 u'television': [u'\u7535\u89c6', u''],
 u'thank you': [u'\u8c22\u8c22', u'\u8c22\u8c22\u4f60']}

In [5]: f.close()

JSON Example

Here we will extend our example to a full translation program that persists its values over time. If the user asks for a word that doesn't have a translation, the user is prompted to enter a translation. The new translation is stored in the dictionary, which is saved when the user types quit.

import json
# Load our dictionary file
with open('chinese.json','r') as f:
    eng_chn_dict = json.load(f)

word = raw_input('Enter English word to translate, or "quit" to quit: ')

while word.lower() != 'quit':
    if word in eng_chn_dict.keys():
        print "'{}' in Chinese has the following translation(s):".format(word)
        translations = eng_chn_dict[word]

        for translation in translations:
            print translation

    else:
        print "'{}' is not in the dictionary.".format(word)
        translation = raw_input('Please enter the translation for {}: '.format(word))

        # This code stores the new translation in the dictionary.
        trans_list = eng_chn_dict.get(word,[])
        trans_list.append(translation)
        eng_chn_dict[word] = trans_list

    word = raw_input('Enter English word to translate, or "quit" to quit: ')

# When the user is done, save the updated dictionary
with open('chinese.json','w') as f:
    json.dump(eng_chn_dict,f)

print "Thank you for playing!"

results matching ""

    No results matching ""