python處理json文件的四個常用函數(shù)
一,json.load()和json.dump只要用于讀寫json數(shù)據(jù)
1json.load()
從文件中讀取json字符串
with open('data.json','r',encoding='utf-8') as f
print(json.load(f))2json.dump()
將json字符串寫入到文件中
content="{'name':'zhangsan','age':18}"
with open('text.json','w',encoding='utf-8') as f:
json.dump(content,f)二,json.loads和json.dumps主要用于字符串和字典之間的類型轉(zhuǎn)換
3json.loads()
將json字符串轉(zhuǎn)換成字典類型
content="{'name':'zhangsan','age':18}"
json.loads(content)3json.dumps()
將字典類型轉(zhuǎn)換成json字符串
content={'name':'zhangsan','age':18}#假設(shè)這個是python定義的字典三,練習(xí)
編寫單詞查詢系統(tǒng):

1編寫一個json格式的文件
{
"one": ["數(shù)字1"],
"two": ["數(shù)字2"],
"too": ["太","也","非常"]
}2編寫python方法
import json
from difflib import get_close_matches
data = json.load(open("data.json","r",encoding="utf-8"))
def translate(word):
word = word.lower()
if word in data:
return data[word]
elif len(get_close_matches(word,data.keys(),cutoff=0.5)) > 0:
yes_no = input("你要查詢的是不是%s?,請輸入yes或no:"%get_close_matches(word,data.keys(),cutoff=0.5))
yes_no = yes_no.lower()
if yes_no == "yes":
return data[get_close_matches(word,data.keys(),cutoff=0.5)[0]]
else:
return "你要查找的內(nèi)容庫里沒有"
word = input("請輸入你要查詢的單詞")
output = translate(word)
if type(output) == list:
for item in output:
print(item)
else:
print(output)到此這篇關(guān)于python處理json文件的四個常用函數(shù)的文章就介紹到這了,更多相關(guān)python處理json文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
windows下Python實現(xiàn)將pdf文件轉(zhuǎn)化為png格式圖片的方法
這篇文章主要介紹了windows下Python實現(xiàn)將pdf文件轉(zhuǎn)化為png格式圖片的方法,結(jié)合實例形式較為詳細(xì)的分析了Python實現(xiàn)將pdf轉(zhuǎn)換為png格式的相關(guān)模塊、使用方法與相關(guān)注意事項,需要的朋友可以參考下2017-07-07
python基礎(chǔ)學(xué)習(xí)之生成器與文件系統(tǒng)知識總結(jié)
本文是參考《python數(shù)據(jù)分析》的附錄對生成器和文件系統(tǒng)結(jié)合案例的一個簡單回顧,文中對python生成器與文件系統(tǒng)作了非常詳細(xì)的介紹,對正在學(xué)習(xí)python的小伙伴們有很好地幫助,需要的朋友可以參考下2021-05-05

