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

  小编写这篇文章的主要目的,主要是给大家介绍,在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定义的字典

  三,练习

  编写单词查询系统:

0.png

  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://www.cloudads.cn/archives/3972.html

发表评论

登录后才能评论