python处理json文件的四个常用函数
作者:wx5d4124a358e8a??????? 时间:2023-01-17 21:26:58
一,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定义的字典
三,练习
编写单词查询系统:
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
标签:python,处理,json,文件,函数
0
投稿
猜你喜欢
基于prototype扩展的JavaScript常用函数库
2023-08-24 15:09:57
Go 语言进阶freecache源码学习教程
2023-08-06 03:05:20
Jupyter Notebook读入csv文件时出错的解决方案
2021-09-15 18:13:48
firefox通过XUL实现text-overflow:ellipsis的效果
2008-07-08 19:12:00
vue.js 实现点击展开收起动画效果
2024-05-29 22:47:44
用python删除文件夹中的重复图片(图片去重)
2021-07-23 22:42:36
详解Python中的array数组模块相关使用
2021-03-05 04:04:19
python3 xpath和requests应用详解
2022-10-13 18:24:36
python轻量级orm框架 peewee常用功能速查详情
2021-10-22 20:43:52
windows10在visual studio2019下配置使用openCV4.3.0
2021-10-23 12:23:31
Python使用Pandas库常见操作详解
2022-12-10 09:03:13
SqlServer编写数据库表的操作方式(建库、建表、修改语句)
2024-01-15 11:38:57
微信公众平台网页授权获取用户基本信息中授权回调域名设置的变动
2023-11-14 14:01:31
JavaScript变量声明var,let.const及区别浅析
2024-05-09 15:05:37
mysql中的保留字段产生的问题
2024-01-14 06:30:58
Python编程实现凯撒密码加密示例
2021-04-22 01:58:56
js实现本地持久化存储登录注册
2024-04-16 10:35:05
Vue使用vux-ui自定义表单验证遇到的问题及解决方法
2024-05-10 14:18:07
python 机器学习之支持向量机非线性回归SVR模型
2022-06-17 20:23:55
教你使用vue-autofit 一行代码搞定自适应可视化大屏
2024-05-09 09:05:53