程式設計(Python)實驗九 檔案與資料格式化
阿新 • • 發佈:2021-02-09
技術標籤:Python程式設計實驗(SWUST)python
實驗目的
- 掌握檔案的基本操作
- 理解一、二維和高維資料的格式化過程
- 掌握 csv 和 json 格式的相互轉換
- 綜合應用組合資料型別與 CSV 和 JSON 資料格式編寫簡單的應用程式
實驗內容
練習一
題目
將提供的 test.csv 檔案,具體內容如下:
程式設計讀入該檔案,轉換成 JSON 格式檔案,並以檔名 out.json 輸出。轉換
後的結果如下所示:
[
{
“同比”: “120.7”,
“城市”: “北京”,
“定基”: “121.4”,
“環比”: “101.5”
},
{
“同比”: “127.3”,
“城市”: “上海”,
“環比”: “101.2”
}
….
]
程式碼
#方法一:
import json
fr = open("test.csv","r")
ls = []
for line in fr:
line = line.replace("\n","")
ls.append(line.split(','))
fr.close()
fw = open("test.json","w")
for i in range(1,len(ls)):
ls[ i]= dict(zip(ls[0],ls[i]))
json.dump(ls[1:],fw,sort_keys=True,indent=4,ensure_ascii=False)
fw.close()
#方法二:
import json
with open("test.csv","r") as fr:
ls = []
for line in fr:
line = line.replace("\n", "")
ls.append(line.split(','))
fr. close()
fw = open("test.json","w")
for i in range(1,len(ls)):
ls[i]= dict(zip(ls[0],ls[i]))
json.dump(ls[1:],fw,sort_keys=True,indent=4,ensure_ascii=False)
fw.close()
練習二
題目
編寫程式製作英文學習字典,詞典基本功能如下:
(1) 程式讀取原始檔路徑下的 txt 格式詞典檔案,若沒有就建立一個。 詞典檔案儲存方式為 “英文單詞 中文單詞”,每行僅有一對中英文釋義;
(2) 程式有新增功能,輸入英文單詞,如果沒有可以新增中文釋義,如果有就顯示”已經存在,不能新增”;
(3) 程式有查詢功能,如果存在,則顯示其中文釋義,不存在就顯示不存在;
(4) 程式有正常退出的操作。
程式碼
import os
keys = []
dic = {}
def readdict():
if os.path.exists("dictionary.txt"):
fr = open('dictionary.txt','r')
else:
fr = open('dictionary.txt','w+')
for line in fr:
line = line.replace("\n","")
v = line.split(':')
dic[v[0]]= v[1]
keys.append(v[0])
fr.close()
def writedict(key,value):
with open('dictionary.txt','a')as fw:
fw.write(key+':'+value+'\n')
def mydict():
n = input("請輸入進入相應模組(新增,查詢,退出)")
if n == "新增":
key = input("請輸入英文單詞:")
if key not in keys:
value =input("字典中未找到單詞'{}'的中文釋義,請輸入該單詞的中文意思,新增進字典中!".format(key))
dic[key] = value
keys.append(key)
writedict(key,value)
else:
print("單詞'{}'已存在,不能新增".format(key))
return 0
elif n == "查詢":
key = input("請輸入英文單詞:")
if key not in keys:
print("英文單詞'{}'不在字典內".format(key))
else:
print(dic[key])
return 0
elif n == "退出":
return 1
else:
print("輸入有誤")
return 0
def main():
readdict()
while True:
n = mydict()
if n == 1:
break
if n == 0:
continue
main()