我想知道是否可以在python中聚合新的值。在
例如,一个JSON值如下所示:
{"time": {"Friday": {"20:00": 2, "19:00": 1, "22:00": 10, "21:00": 5,
"23:00": 14, "0:00": 2, "18:00": 2}, "Thursday": {"23:00": 1,
"0:00": 1, "19:00": 1, "18:00": 1, "16:00": 2, "22:00": 2},
"Wednesday": {"17:00": 2, "23:00": 3, "16:00": 1, "22:00": 1,
"19:00": 1, "21:00": 1}, "Sunday": {"16:00": 2, "17:00": 2, "19:00": 1,
"22:00": 4, "21:00": 4, "0:00": 3, "1:00": 2}, "Saturday":
{"21:00": 4, "20:00": 3, "23:00": 10, "22:00": 7, "18:00":
1, "15:00": 2, "16:00": 1, "17:00": 1, "0:00": 8, "1:00":
1}, "Tuesday": {"19:00": 1, "17:00": 1, "1:00": 2, "21:00":
1, "23:00": 3}, "Monday": {"18:00": 2, "23:00": 1, "22:00": 2}}
我想把它汇总起来,根据它开放的时间分为四类。在
这四类是:
早上6点到中午12点:早上
中午12点-下午5点:下午
下午5点至11点:晚上
晚上11点-早上6点:晚上
例如:
如果这是当前值:
^{pr2}$则输出应为:
"Friday": {"morning": 0, "afternoon": 0, "evening": 15, "night": 0}
因此输出应该是
"Day": {"morning": count, "afternoon": count, "evening": count, "night":count}
对于数百个JSON值。在
我的想法是我可以创建4个代表每个时区的箱子。然后我将使用两个for循环来遍历每一天的值。如果值在bucket的范围内,我会把它加到计数中。然后我将把这一天存储在一个字典中,其值也是一个字典。内部字典由四个时区组成,以count为值。然后我会把这一天还给你,然后每天重新开始。在
到目前为止我还需要实现什么函数。在
import json
from datetime import datetime
def cleanStr4SQL(s):
return s.replace("'","`").replace("\n"," ")
def parseCheckinData():
#write code to parse yelp_checkin.JSON
with open('yelp_checkin.JSON') as f:
outfile = open('checkin.txt', 'w')
line = f.readline()
count_line = 0
while line:
data = json.loads(line)
outfile.write(cleanStr4SQL(str(data['business_id'])) + '\t')
outfile.write(aggregate(cleanStr4SQL(str(data['time']))))
line = f.readline()
count_line+=1
print(count_line)
outfile.close()
f.close()
def aggregate(line):
morning = []
afternoon = []
evening = []
night = []
for l in line:
print(l)
我想知道用python解决这个问题的最佳方法是什么。在
如有任何建议,我们将不胜感激。我知道没有代码,但如果有人能给我指明方向那就太好了。在
谢谢你的阅读
这里有一种可能的方法。我只尝试了一个json字符串,因此您可能需要扩展它来处理多次出现的情况。在
希望有帮助
相关问题 更多 >
编程相关推荐