1. 提取data.json中的数据,将每条数据中的name、text、love和comment信息。并且保存到另外一个json文件中
import json
with open('./homework/data.json','r',encoding='utf-8') as f:
content =json.load(f)
print(content)
for item in content['data']:
print(item['name'])
new_name = []
new_name.append(item['name'])
with open('./homework/new_name','w',encoding='utf-8') as f1:
json.dump(new_name,f1)
for item in content['data']:
print(item['text'])
new_text = []
new_text.append(item['text'])
with open('./homework/new_text','w',encoding='utf-8') as f2:
json.dump(new_text,f2)
for item in content['data']:
print(item['love'])
new_love = []
new_love.append(item['love'])
with open('./homework/new_love','w',encoding='utf-8') as f3:
json.dump(new_love,f3)
for item in content['data']:
print(item['comment'])
new_comment = []
new_comment.append(item['comment'])
with open('./homework/new_comment','w',encoding='utf-8') as f4:
json.dump(new_comment,f4)
2.统计data.json中comment数量超过1000的个数
for item in new_comment:
count = 0
if int(item) > 1000:
count += 1 # 统计个数
print(count)
3.将data.json文件中所有点赞数(love)对应的值超出1000的用k来表示,例如1000修改为1k, 1345修改为1.3k
for item in new_love:
str1 = ''
if int(item) > 1000: # 分出大于1000的数
str1 = str(int(item) // 100 / 10)
str2 = str1 + 'k'
print(str2)
4.写猜数字游戏,如果输入有误,提示重新输入,直达输入正确为止。比如:输入数字的时候没有按要求输入,提示重新输入
import random
number = random.randint (0,1000)
while True:
try:
num = input('请输入数字:')
if int (num) == number:
print ('恭喜你,猜对了!')
elif int(num) > number:
print('太大了,再小点')
else:
print('太小了,再大点')
except:
print('输入错误,请重新输入')
网友评论