您现在的位置是:网站首页> 编程资料编程资料

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

2023-05-26 417人已围观

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

一,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)

到此这篇关于python处理json文件的四个常用函数的文章就介绍到这了,更多相关python处理json文件内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

-六神源码网