1. 提取data.json中的数据,将每条数据中的name、text、love和comment信息。并且保存到另外一个json文件中
import json
with open('./data1/data.json', encoding='utf-8') as f:
a = json.load(f) # a为data.json中的内容
value1 = a['data'] # value1为a中'data'对应的value值为列表,里面有多个字典
list1 = []
dict2 = {}
for dict1 in value1: # 遍历value1中的每个字典出来
for key1 in dict1:
if key1 == 'name':
# dict2 = dict1.pop(key1)
dict2[key1] = dict1[key1]
list1.append(dict2)
elif key1 == 'text':
dict2[key1] = dict1[key1]
list1.append(dict2)
elif key1 == 'love':
dict2[key1] = dict1[key1]
list1.append(dict2)
elif key1 == 'comment':
dict2[key1] = dict1[key1]
list1.append(dict2)
print(list1)
with open('./data1/new_data.json', 'w', encoding='utf-8') as g:
json.dump(list1, g)
print(g)
2. 统计data.json中comment数量超过1000的个数
import json
with open('./data1/data.json', encoding='utf-8') as f:
a = json.load(f) # a为data.json中的内容
value1 = a['data'] # value1为a中'data'对应的value值为列表,里面有多个字典
num1 = 0
for dict1 in value1:
if dict1['comment'] >= '1000':
num1 += 1
print(num1)
3. 将data.json文件中所有点赞数(love)对应的值超出1000的用k来表示,例如1000修改为1k, 1345修改为1.3k
with open('./data1/data.json', encoding='utf-8') as f:
a = json.load(f) # a为data.json中的内容
value1 = a['data'] # value1为a中'data'对应的value值为列表,里面有多个字典
for dict1 in value1:
if dict1['love'] >= '1000':
print(dict1['love'])
4. 写猜数字游戏,如果输入有误,提示重新输入,直达输入正确为止。比如:输入数字的时候没有按要求输入,提示重新输入
while True:
try:
num1 = int(input('请输入数字:'))
except:
input('重新输入')
网友评论