40923247 cp2020

  • Home
    • Site Map
    • reveal
    • blog
  • 首頁
  • HW1
    • U13
      • IPv4 and IPv6 Addresses
      • IPv4 Addressing
      • IPv4 Address Classes
      • Assigning an IP Address 分配IP地址
      • IPv6
      • Classful Vs  Classless Addressing  Subnet and CIDR
      • Windows Networking Windows網絡
    • U14
      • Overview 概述
      • TCP and UDP
      • TCP IP Stack
      • Networking Transfer Protocols 網絡傳輸協議
      • FTP
      • SSL
  • HW2
    • 2-1
    • 2-2
    • 2-3
  • HW3
    • Exercise 34 練習34
    • Exercise 24  練習24
    • Exercise 28  練習28
HW3 << Previous Next >> Exercise 24  練習24

Exercise 34 練習34

Birthday Json 傑森生日  

This exercise is Part 2 of 4 of the birthday data exercise series. The other exercises are: Part 1, Part 3, and Part 4.

In the previous exercise we created a dictionary of famous scientists’ birthdays. In this exercise, modify your program from Part 1 to load the birthday dictionary from a JSON file on disk, rather than having the dictionary defined in the program.

Bonus: Ask the user for another scientist’s name and birthday to add to the dictionary, and update the JSON file you have on disk with the scientist’s name. If you run the program multiple times and keep adding new names, your JSON file should keep getting bigger and bigger.

此練習是生日數據練習系列4的第2部分。其他練習是:第1部分,第3部分和第4部分。

在上一個練習中,我們創建了著名科學家生日字典。在本練習中,請修改第1部分中的程序,以從磁盤上的JSON文件加載生日字典,而不是在程序中定義字典。

獎勵:向用戶詢問另一個科學家的名字和生日,以添加到詞典中,並使用科學家的名字更新磁盤上的JSON文件。如果您多次運行該程序並繼續添加新名稱,那麼JSON文件應該會越來越大。

Discussion 討論區

In a previous exercise we talked about how to save information to a .txt file on disk, but in this exercise we are talking about writing a different kind of file format called JSON.

The JSON file format was developed in the early 2000s as a standard for how web servers would pass data back and forth. It is still used for web server communication today, and it conveniently is also a way we can store dictionary-like data in a file on disk. The JSON format specifies a way to serialize (turn into a string) a dictionary or list, which then means that string can be written to disk or passed to another application. JSON is meant to store dictionary-like data both in a readable way for humans, and in a compact way that can be read by computers. Because it is a standard format, you can write JSON in one language and read JSON from another language to effectively pass information between the two programs or applications. You can read more about the history of JSON on the wikipedia article.

Here is an example of JSON:

在上一個練習中,我們討論瞭如何將信息保存到磁盤上的.txt文件中,但是在本練習中,我們正在討論編寫另一種稱為JSON的文件格式。

JSON文件格式是在2000年代初期開發的,它是Web服務器如何來回傳遞數據的標準。如今,它仍用於Web服務器通信,它也是我們可以將類似字典的數據存儲在磁盤上的文件中的一種便捷方式。JSON格式指定了一種對字典或列表進行序列化(轉換為字符串)的方式,這意味著可以將字符串寫入磁盤或傳遞給另一個應用程序。JSON旨在以人類可讀的方式以及計算機可以讀取的緊湊方式存儲類似字典的數據。因為它是一種標準格式,所以您可以用一種語言編寫JSON並從另一種語言讀取JSON,以在兩個程序或應用程序之間有效地傳遞信息。您可以在上閱讀有關JSON歷史的更多信息維基百科文章。

這是JSON的示例:

{
    "name": "Michele",
    "shirt_color": "blue",
    "laptops": [
    {
        "brand": "Lenovo",
        "operating_system": "Ubuntu"
    },
    {
        "brand": "Apple",
        "operating_system": "OSX"
    }
    ],
    "has_a_dog": false,
    "items_on_desk": ["mug", "pen", "monitor"]
}

Notice how you can mix dictionaries and lists. In this example the top-level container is a dictionary, with the keys name, shirt_color, laptops, has_a_dog, and items_on_desk. The keys can be lists, strings, booleans, or other dictionaries. Usually you don’t write JSON by hand (but it is very readable so you easily could). One of my favorite tools to test whether you’ve written valid JSON is this free JSON validator - just paste your JSON in there and it tells you if it will be read by a program that understands JSON.

There is a built-in Python library for reading and writing JSON files, so you don’t have to worry about how your dictionaries and lists are going to be turned into the right format!

As long as the data you want to store is either a dictionary or a list of dictionaries, writing JSON is straightforward. First, import the json library (no installation needed, it is built in to Python) and initialize some dictionary:

注意如何混合使用字典和列表。在這個例子中頂層容器是一個字典,與鍵name,shirt_color,laptops,has_a_dog,和items_on_desk。鍵可以是列表,字符串,布爾值或其他字典。通常,您不需要手工編寫JSON(但它具有很高的可讀性,因此您可以輕鬆編寫)。這個免費的JSON驗證程序是我最喜歡的測試您是否已編寫有效JSON的工具之一-只需將JSON粘貼在其中,它就會告訴您是否會由理解JSON的程序讀取它。

有一個內置的Python庫用於讀寫JSON文件,因此您不必擔心字典和列表將如何轉換為正確的格式!

只要您要存儲的數據是字典還是詞典列表,編寫JSON就很簡單。首先,導入json庫(無需安裝,它內置在Python中)並初始化一些字典:

import json

info_about_me = {
    "name": "Michele",
    "has_a_dog": False
}

Then, to save your dictionary to disk you need to open a file and use the json.dump() method.
Remember to use the 
w flag when opening a file for writing:
然後,要將字典保存到磁盤,您需要打開一個文件並使用該json.dump()方法。w打開文件進行寫入時,請記住使用
該
標誌:

with open("info.json", "w") as f:
    json.dump(info_about_me, f)

And you will have saved a file called info.json in the same directory as your Python program.
The dictionary 
info_about_me will be saved to disk, but the variable name will not be.
Basically, JSON won’t remember the name of the variable you saved your dictionary in.
If you open the file with a text editor (Notepad++, vim, emacs, Sublime Text, etc.), you
will just see:
您將info.json在與Python程序相同的目錄中保存一個名為的文件。詞典info_about_me將保存到磁盤,但變量名
不會。
基本上,JSON不會記住保存字典的變量的名稱。如果使用文本編輯器(Notepad ++,vim,emacs,Sublime Text等)
打開文件,則只會看到:

{
    "name": "Michele",
    "has_a_dog": false
}

Alternatively, you can also manually create a JSON file and type JSON directly into it (passing it through the JSON validator of course!). Just save the file with the .json extension and copy the dictionary directly into the file.

Now I can use the information about me that I saved to disk in another program (written in a completely different file) to do something like printing a message. When I saved the JSON file, the variable name of my dictionary was not saved with it, so when I load the JSON file I need to save it into a variable. I can use the same json library to do this:

另外,您也可以手動創建一個JSON文件,然後直接在其中鍵入JSON(當然,還要通過JSON驗證器!)。只需保存帶有.json擴展名的文件,然後將字典直接複製到文件中即可。

現在,我可以使用保存在另一個程序中的有關我的信息(以完全不同的文件編寫)來執行類似打印消息的操作。當我保存JSON文件時,字典的變量名並未隨之保存,因此,當我加載JSON文件時,需要將其保存到變量中。我可以使用相同的json庫來執行此操作:

import json

with open("info.json", "r") as f:
    info = json.load(f)

if info["has_a_dog"]:
    print("{} has a dog".format(info["name"]))
else:
    print("{} does not have a dog".format(info["name"]))

When this program runs, the output should be:
運行該程序時,輸出應為:
Michele does not have a dog

Notice how when I loaded the JSON file I used a different name than when I saved it - this is because the variable names don’t get saved together with the JSON data, so you do not have to use the same variable names to save and load JSON.

Now that you know about JSON, you can use it to do a number of things:

  • Save data to disk that can be shared by people and programs.
  • Constantly update data that needs to be shared by re-saving and re-load to disk.
  • Save data from a program that a human can read and manually check and fix errors.

請注意,加載JSON文件時使用的名稱與保存時使用的名稱不同-這是因為變量名稱不會與JSON數據一起保存,因此您不必使用相同的變量名稱進行保存和加載JSON。

現在,您已經了解了JSON,可以使用它來做很多事情:

  • 將數據保存到可以由人員和程序共享的磁盤。
  • 不斷更新需要通過重新保存並重新加載到磁盤的數據。
  • 保存人類可以讀取的程序中的數據,並手動檢查和修復錯誤。

Solutions 解決方案

Sample solution 範例解答

Here is one reader’s solution to the exercise:

這是該練習的一個讀者解決方案:

import json

birthday = {}
with open('birthdays.json', 'r') as f:
          birthday = json.load(f)

def add_entry():
    name = input('Who do you want to add to the Birthday Dictionnary?\n').title()
    date = input('When is {} born?\n'.format(name))
    birthday[name] = date
    with open('birthdays.json', 'w') as f:
        json.dump(birthday, f)
    print('{} was added to my birthday list\n'.format(name))

def find_date():
    name = input("who's birthday do you want to know?\n").title()
    try :
        if birthday[name]:
            print('{} is born on {}\n'.format(name, birthday[name]))
    except KeyError:
        print('{} is not in the list\n'.format(name))

def list_entries():
    print('The current entries in my birthday list are:\n============================================')
    for key in birthday:
        print(key.ljust(31), ':', birthday[key])
    print()

while True:
    what_next = input('What do you want to do next? you can: Add, Find, List, Quit\n').capitalize()
    if what_next == 'Quit':
        print('Good Bye')
        raise SystemExit(0)
    elif what_next == 'Add':
        add_entry()
    elif what_next == 'Find':
        find_date()
    elif what_next == 'List':
        list_entries()


HW3 << Previous Next >> Exercise 24  練習24

Copyright © All rights reserved | This template is made with by Colorlib