exercise

  1. 提取data.json中的数据,将每条数据中的name、text、love和comment信息。并且保存到另外一个json文件中
import json
with open('./files/data.json','r',encoding='utf-8') as f:
    content = json.load(f)

list2 = []
list1 = content['data']
for item in list1[:]:
    name = item['name']
    text = item['text']
    love = item['love']
    comment = item['comment']
    info1 = {'name': name, 'text': text, 'love': love, 'comment': comment}
    list2.append(info1)
print(list2)
with open('./files/info.json','w',encoding='utf-8') as f:
    json.dump(list2,f)
exercise_第1张图片
image.png

2.统计data.json中comment数量超过1000的个数

import  json
with open('./files/data.json','r',encoding='utf-8') as f:
    content = json.load(f)
list1 = content['data']
count1 = 0
for item in list1:
    if int(item['comment']) >1000:
        count1 += 1
print(count1)
exercise_第2张图片
image.png
  1. 将data.json文件中所有点赞数(love)对应的值超出1000的用k来表示,例如1000修改为1k, 1345修改为1.3k
import  json
with open('./files/data.json','r',encoding='utf-8') as f:
    content = json.load(f)
list1 = content['data']
for item in list1:
    if int(item['love']) > 1000:
        love = int(item['love'])//100/10
        item['love'] = str(love)+'k'
with open('./files/data.json','w',encoding='utf-8') as f:
     json.dump(content,f)

4.写猜数字游戏,如果输入有误,提示重新输入,直达输入正确为止。比如:输入数字的时候没有按要求输入,提示重新输入

import random
number1 = random.randint(1,100)
try:
    while True:
        num1 = int(input('请输入一个数字(1-100):'))
        if num1 > number1 and num1<=100:
            print('大了大了')
        elif num1 < number1 and num1>=0:
            print('小了小了')
        elif num1 == number1:
            print('恭喜你,猜对了!')
            break
except ValueError:
        print('输入有误,请重新输入')
  1. 写学生管理系统的添加学生功能(数据需要本地化),要求除了保存学生的基本信息以外还要保存学生的学号,但是学号需要自动生成,生成原则:
    添加第一个学生对应的学号是:py001
    第二次添加的学生的学号是:py002
    ...
    如果前面的学生因为各种原因被移除了,那后面添加学生的时候原则不变,就是比如上次已经添加到py012,那么前面不管有没有删除情况,再次添加学生的学号是py013
import json
dict1={}
with open('./files/stuinfo.json','r',encoding='utf-8') as f:
    content=json.load(f)

num = content.get('number')
num += 1
id = 'python1806'+str(num).rjust(3,'0')
name = input('姓名:')
age = input('年龄:')
tel = input('电话:')

#创建学生
dict1['name']=name
dict1['age'] = age
dict1['tel'] = tel
dict1['id'] = id

content['students'].append(dict1)
content['number']=num
with open('./files/stuinfo.json','w',encoding='utf-8') as f:
    json.dump(content,f)


#{"number": 0, 
"students": [
{"name": "name", "age": "age", "tel": "tel", "id": "id"}
  ]
}
#json文件结构

你可能感兴趣的:(exercise)