羅
羅左欣 8 years ago
可是我現在整個人被 Python 整慘呀xd
羅
羅左欣 8 years ago
參考 - 你不可不知的 JSON 基本介紹
- 20151014 [KUASITC] Python社課筆記(3)
- [ 筆記內容 ] 高雄市政府開放資料--輕輕鬆鬆找到測速照相機
- [ 課堂程式 ] GitHub
- [ 補充資料 ]
- (一)基本概念
- 1. Python - 好用的原因
- 2. JavaScript Object Notation - Json
- 3. Python - 讀取檔案
- [ 用法 ] open()
- [ 原檔 ] camera.json 檔
- [ 範例 ] 讀取 camera.json
- 4. Python - 將"字串"轉成"json object"
- [ 用法 ] json.load()
- (二)課堂題目 -- 高雄市政府開放資料-輕輕鬆鬆找到測速照相機!
- STEP_1 : 先得到 json 的檔案
- STEP_2 : 把 "文字檔" 讀成 json object
- STEP_3 : 利用迴圈寫出查詢
- [ 完整程式碼 ]
- [ 範例程式碼 -- 註解版 ] By Aweimeow 大大
(一)基本概念
# 範例用法
open_file = open( 'file_name', 'r' ) # 使用"open()"指定目的檔、設定讀寫模式
output = open_file.read() # 將讀取到的檔案內容存入變數"output"內
print( output )
# lesson_3_1.py
open_file = open( 'camera.json', 'r', encoding = 'utf-8' ) # encoding = '' 設定解讀編碼
s = open_file.read()
print( s )
# 範例用法
import json # 要使用"json.loads()"前,必須先載入"json"
json_object = json.loads( string )
(二)課堂題目 -- 高雄市政府開放資料-輕輕鬆鬆找到測速照相機!
# lesson_3_2.py
import json # 載入 json
## 1. 讀取"camera.json",並把它轉成"object"
open_file = open('camera.json', 'r', encoding = 'utf-8') # 將讀取編碼設為"utf-8"
tmp_files = open_file.read()
input_data = json.loads(tmp_files) # 把 json 檔案改成 object
open_file.close() # 關閉檔案
## 2. 提示使用者輸入欲查詢的路名(要用中文)
# 讓使用者輸入資料
user_input = input('Please use chinese to enter road name in Kaohsiung : ')
# 過濾資料
user_input = user_input.replace('路', '')
## 3. 在查詢結果前,在螢幕上顯示"項目意義"
print('行政區\t測照方向\t測照地點')
print('*' * 50) # 用來產生分隔線
## 4. 查詢輸入的資料
for data in input_data: # 依照資料的筆數("input_data")進行迴圈
# 判斷資料裡面是否有我們要找的東西
if user_input in data['測照地點']:
print('%s\t%s\t\t%s' % (data['行政區'], data['測照方向'], data['測照地點']))
# lesson_3_2(teach).py
import json
## 1. 讀取"camera.json"檔,設定讀取編碼為 : "utf-8"
f = open( 'camera.json ', 'r', encoding = 'utf-8' ) # 開啟檔案
s = f.read() # 將讀取的內容存至"s"
f.close() # 關閉檔案
## 2. 把"文字檔"轉換 json object
json_obj = json.loads( s ) # 將"s"的內容轉換成"json_obj"
## 3. 提供使用者查詢資料
# 讓使用者輸入內容
user_input = input( '高雄市區監視器分佈位置查詢(請輸入路名): ' )
# 如果使用者輸入的字串裡有'路'這個字,把它取代變成''
user_input = user_input.replace( '路', '' )
## 4. 利用迴圈查詢資料,並將結果輸出
# 標明輸出結果的意義,讓版面整齊排列
print( '行政區\t測照方向\t測照地點' )
print( '=' * 50 )
# 利用迴圈寫出查詢
for obj in json_obj:
if user_input in obj[ '測照地點' ]:
print( '%s\t%s\t\t%s' % (obj[ '行政區' ], obj[ '測照方向' ], obj[ '測照地點' ]) )