Python中处理JSON文件时,json.load()函数应用频率最高的四个函数是?
- 内容介绍
- 文章标签
- 相关推荐
本文共计358个文字,预计阅读时间需要2分钟。
1. 使用json.load()读取JSON数据:pythonwith open('data.json', 'r', encoding='utf-8') as f: print(json.load(f))
2. 使用json.dump()写入JSON数据到文件:pythoncontent='{name: zh}'with open('output.json', 'w', encoding='utf-8') as f: json.dump(content, f)
一,json.load()和json.dump只要用于读写json数据
1json.load()
从文件中读取json字符串
with open('data.json','r',encoding='utf-8') as fprint(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 jsonfrom 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)
本文共计358个文字,预计阅读时间需要2分钟。
1. 使用json.load()读取JSON数据:pythonwith open('data.json', 'r', encoding='utf-8') as f: print(json.load(f))
2. 使用json.dump()写入JSON数据到文件:pythoncontent='{name: zh}'with open('output.json', 'w', encoding='utf-8') as f: json.dump(content, f)
一,json.load()和json.dump只要用于读写json数据
1json.load()
从文件中读取json字符串
with open('data.json','r',encoding='utf-8') as fprint(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 jsonfrom 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)

