网络编程
位置:首页>> 网络编程>> Python编程>> python处理json文件的四个常用函数

python处理json文件的四个常用函数

作者:wx5d4124a358e8a???????  发布时间:2023-01-17 21:26:58 

标签:python,处理,json,文件,函数

一,json.load()和json.dump只要用于读写json数据

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主要用于字符串和字典之间的类型转换

3json.loads()

将json字符串转换成字典类型

content="{'name':'zhangsan','age':18}"
json.loads(content)

3json.dumps()

将字典类型转换成json字符串

content={'name':'zhangsan','age':18}#假设这个是python定义的字典

三,练习

编写单词查询系统:

python处理json文件的四个常用函数

1编写一个json格式的文件

{
"one": ["数字1"],
"two": ["数字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 "你要查找的内容库里没有"
word = input("请输入你要查询的单词")
output = translate(word)
if type(output) == list:
for item in output:
print(item)
else:
print(output)

来源:https://blog.51cto.com/tyjs09/5462027

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com