Python:全局作用于字典而不是单个类Dict

时间:2018-10-29 11:22:38

标签: python

我正在尝试通过JSON进行python循环,并将数据分解为Year,Month和day概览计数。因此,我创建了一个循环,该循环将遍历数据的每一年,并创建Year类,然后将其添加到关注者计数中。

在Year类中创建月份时会出现问题。它似乎影响每个班级,而不影响我选择的年级。我知道我还没有很好地解释这一点,但是如果您查看下面的数据和输出,即使数据在两个不同的年份进行设置,也可以看到01设置了两次。

代码

带有在线IDE的代码:https://repl.it/repls/DefenselessNeatLifecycle

测试数据

 {
  "followers": {
    "user1": "2018-10-25T08:44:32",
    "user2": "2017-01-25T08:44:03",
    "user3": "2017-03-25T08:43:22",
    "user4": "2016-01-25T08:40:24",
    "user5": "2015-12-25T08:40:06",
    "user6": "2015-12-21T08:40:06"
  }
}

输出

2015 2
2015 {u'03': 1, u'12': 2, u'01': 2, u'10': 1}
2016 1
2016 {u'03': 1, u'12': 2, u'01': 2, u'10': 1}
2017 2
2017 {u'03': 1, u'12': 2, u'01': 2, u'10': 1}
2018 1
2018 {u'03': 1, u'12': 2, u'01': 2, u'10': 1}

输出应显示的内容

2015 2
2015 {u'12': 2}
2016 1
2016 {u'01': 1}
2017 2
2017 {u'01': 1, u'03': 1}
2018 1
2018 {u'10': 1}

main.py

import json
import operator
from pprint import pprint
from year import Year

json_reference = "test-data.json"
p1 = {}

with open(json_reference, 'r') as f:
    json_data = json.load(f)

    def report_complete(a):
        print("100%")

        for year in sorted(p1):
            # Print Top Line Year Totals
            print(year, p1[year].follower_count)

            # Print Top Line Month Totals
            print(year, p1[year].months)

    def percent_report(loop):
        follower_total = len(json_data["followers"])
        percentage_complete = int(loop / float(follower_total) * 100)
        # print "{0:.0f}%".format(percentage_complete)

    for i, lines in enumerate(json_data["followers"]):
        joined_date = json_data["followers"][lines]
        year = joined_date[0:4]
        month = joined_date[5:7]

        if year in p1:
            p1[year].add_follower(month)
        else:
            anew = Year(year)
            anew.add_follower(month)
            p1.update({year: anew})

        if i % 10000 == 0:
            percent_report(i)

        if i + 1 == len(json_data["followers"]):
            report_complete(i)

年级

class Year:
    follower_count = 0
    months = {}

    def __init__(self, year):
        self.year = year

    def create_new_month(self, month):
        self.months.update({month: 1})

    def add_follower(self, month):
        self.follower_count += 1

        if month in self.months:
            self.months[month] += 1
            # print self.months[month]
        else:
            self.create_new_month(month)
            print(month)

0 个答案:

没有答案