Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python对象调用错误_Python - Fatal编程技术网

Python对象调用错误

Python对象调用错误,python,Python,您好,我是python语言的新手,在运行test.py文件时遇到以下错误 Traceback (most recent call last): File "D:/Py Charm projects/Example/test.py", line 3, in <module> repository = Repository(Config) File "D:\Py Charm projects\Example\repository.py", line 29, in __init__

您好,我是python语言的新手,在运行test.py文件时遇到以下错误

Traceback (most recent call last):

File "D:/Py Charm projects/Example/test.py", line 3, in <module>

repository = Repository(Config)

File "D:\Py Charm projects\Example\repository.py", line 29, in __init__

assert isinstance(config, Config)
AssertionError
repository.py

from repository import Repository
from configuration import Config
repository = Repository(Config)
dataset, labels = repository.get_dataset_and_labels()
import json
import re
import time
from random import random
from glob import glob
from os.path import basename, dirname
from os.path import sep as path_sep
from os.path import join as path_join
from datetime import datetime

from numpy import inf, array
from pandas import DataFrame
from configuration import Config

__author__ = 'luis'
methods = []


def method_list(method):
if method not in methods:
    methods.append(method)

return method


class Repository(object):
def __init__(self, config):
    self.expert_locations = {}
    assert isinstance(config, Config)
    self.config = config
    self.base_path = config.base_path
    self.config_path = config.config_path
    self.sample_path = config.path_user_sample
    self.expert_data_path = config.expert_data_path
    self.users = []
    self.access_points = {}
    self.locations = {}
    self.goal_types = {}
    self.goals = {}
    self.goals_timetable = {}
    self.samples = {}
    self.expert_samples = {}
    self.expert_validation_samples = {}
    self.fingerprints = {}
    for m in methods:
        m(self)

@method_list
def load_users(self):
    user_file = "%s/users.json" % self.config_path
    with open(user_file) as fd:
        jf = json.load(fd)

    for u in jf:
        self.users.append(u['user_id'])

@method_list
def load_locations(self):
    user_file = "%s/goallist.json" % self.config_path
    with open(user_file) as fd:
        jf = json.load(fd)

    for loc in jf:
        self.locations.setdefault((loc['latitude'], loc['longitude']), set())

@method_list
def load_goals(self):
    file_list = glob('%s/Goals/Goals*/*.json' % self.config_path)
    for f in file_list:
        goal_type = re.match(".*_([a-z]*)", dirname(f)).group(1)
        time_name = basename(f).split(".")[0]
        ts = time.mktime(time.strptime(time_name, "%Y-%m-%d_%H-%M-%S"))
        with open(f) as fd:
            jf = json.load(fd)

        for loc in jf:
            priority = self.goals.setdefault(goal_type, {}).setdefault(ts, {})
            priority[(loc['location']['latitude'], loc['location']['longitude'])] = loc['priority']

    self.goal_types = dict([x[::-1] for x in enumerate(self.goals)])

@method_list
def load_expert_data(self):
    file_list = glob("%s/%s" % (self.expert_data_path, self.config.expert_data_glob_pattern))
    for f in file_list:
        user = re.match(".*StampRally_([a-z]*)/", dirname(f)).group(1)
        time_name = basename(f).split(".")[0]
        ts = time.mktime(time.strptime(time_name, "%Y-%m-%d_%H-%M-%S"))
        with open(f) as fd:
            jf = json.load(fd)

        for fingerprint in jf:
            loc = (fingerprint['location']['latitude'], fingerprint['location']['longitude'])
            for mac, v in fingerprint['fingerprint']['wifi'].items():
                # self.access_points.setdefault(mac, set()).add(loc)
                self.expert_locations.setdefault(loc, set()).add(mac)
                self.expert_samples.setdefault(ts, {}).setdefault(user, {}).setdefault(loc, []).append(
                    {'level': v["level"], 'mac': mac})

@method_list
def load_expert_data_test(self):
    file_list = glob("%s/%s" % (self.expert_data_path, self.config.expert_data_test_glob_pattern))
    for f in file_list:
        user = re.match(".*StampRally_([a-z]*)/", dirname(f)).group(1)
        time_name = basename(f).split(".")[0]
        ts = time.mktime(time.strptime(time_name, "%Y-%m-%d_%H-%M-%S"))
        with open(f) as fd:
            jf = json.load(fd)

        for fingerprint in jf:
            loc = (fingerprint['location']['latitude'], fingerprint['location']['longitude'])
            for mac, v in fingerprint['fingerprint'].items():
                # self.access_points.setdefault(mac, set()).add(loc)
                self.expert_locations.setdefault(loc, set()).add(mac)
                self.expert_validation_samples.setdefault(ts, {}).setdefault(user, {}).setdefault(loc, []).append(
                    {'level': v["level"], 'mac': mac})

@method_list
def load_goals_timetable(self):
    file_list = glob('%s/Goals/Users/*.json' % self.config_path)
    for f in file_list:
        time_name = basename(f).split(".")[0]
        ts = time.mktime(time.strptime(time_name, "%Y-%m-%d_%H-%M-%S"))
        with open(f) as fd:
            jf = json.load(fd)

        try:
            goal_type = jf.values()[0]
        except IndexError:
            continue

        self.goals_timetable.setdefault(ts, []).append(self.goal_types[goal_type])

@method_list
def load_samples(self):
    file_list = glob('%s/StampRally_*/%s/*.json' % (self.config.data_set_path, self.sample_path))
    for f in file_list:
        user = re.match(".*StampRally_([em][0-9])/", dirname(f)).group(1)
        time_name = basename(f).split(".")[0]
        ts = time.mktime(time.strptime(time_name, "%Y-%m-%d_%H-%M-%S"))
        with open(f) as fd:
            jf = json.load(fd)

        for fingerprint in jf:
            loc = (fingerprint['location']['latitude'], fingerprint['location']['longitude'])
            for mac, v in fingerprint['fingerprint']['wifi'].items():
                self.access_points.setdefault(mac, set()).add(loc)
                self.locations[loc].add(mac)
                self.samples.setdefault(ts, {}).setdefault(user, {}).setdefault(loc, []).append(
                    {'level': v["level"], 'mac': mac})

def iter_samples(self, time_filter=None, user_filter=None, loc_filter=None):
    time_filter = time_filter and time_filter or (0., inf)
    user_filter = user_filter and re.compile(user_filter) or re.compile(".*")
    for ts, users in filter(lambda x: time_filter[0] <= x[0] <= time_filter[1], self.samples.items()):
        for u, locations in filter(lambda x: user_filter.search(x[0]), users.items()):
            for loc, fingerprints in filter(lambda x: not loc_filter and True or loc_filter == x[0],
                                            locations.items()):
                for fingerprint in fingerprints:
                    mac = fingerprint['mac']
                    value = fingerprint['level']
                    yield [ts, u, loc, mac, value]

def iter_fingerprints(self, time_filter=None, user_filter=None, loc_filter=None, group_filter=None, src='samples'):
    time_filter = time_filter and time_filter or (0., inf)
    user_filter = user_filter and re.compile(user_filter) or re.compile(".*")
    src = getattr(self, src)
    for ts, users in src.items():
        if not (time_filter[0] <= ts <= time_filter[1]):
            continue

        for u, locations in users.items():
            if not user_filter.search(u):
                continue

            for loc, fingerprints in locations.items():
                if loc_filter and loc_filter != loc:
                    continue

                if group_filter:
                    try:
                        fps = [fp for fp in fingerprints if fp['mac'] in group_filter[loc]]
                    except TypeError:
                        fps = [fp for fp in fingerprints if fp['mac'] in group_filter]
                    except KeyError:
                        fps = fingerprints

                    yield [ts, u, loc, fps]
                    continue

                yield [ts, u, loc, fingerprints]

def get_dataset_and_labels(self, columns=None, **kwargs):
    df = []
    labels = []
    for ts, usr, loc, fingerprint in self.iter_fingerprints(**kwargs):
        fp = dict([(m['mac'], m['level']) for m in fingerprint])
        df.append(fp)
        labels.append(loc)

    return DataFrame(df, columns=columns), array(labels)

def create_time_series(self, time_filter=None, user_filter=None, sample_time=70):
    time_filter = time_filter and time_filter or (0., inf)
    user_filter = user_filter and re.compile(user_filter) or re.compile(".*")
    time_series = []
    for ts, users in filter(lambda x: time_filter[0] <= x[0] <= time_filter[1], self.samples.items()):
        lts = ts
        for u, locations in filter(lambda x: user_filter.search(x[0]), users.items()):
            for loc, fingerprints in locations.items():
                for fingerprint in fingerprints:
                    mac = fingerprint['mac']
                    lts += random()
                    time_series.append([lts, mac])

            lts += sample_time

    return time_series

@method_list
def update_week_specs(self):
    week_stats = {}
    for ts in self.samples:
        date = datetime.fromtimestamp(ts)
        week = date.strftime("%W")
        week_stats.setdefault(week, []).append(ts)

    self.config.week_specs =  dict([("W%s" % w, (min(v), max(v))) for w, v in week_stats.items()])
    self.config.week_names = sorted(self.config.week_specs.keys(), key=lambda x: self.config.week_specs[x][0])
from os.path import sep as path_sep
from os.path import join as path_join


class Config(object):
base_path = "."
date_format = "%Y-%m-%d_%H-%M-%S"
recording_start = 1390202100.0
stages = []
var_fill = -200.
knn_var_fill = -90.
week_specs = {"W03": (1390202100.6, 1390589153.57),
              "W04": (1390806000.32, 1391193208.91),
              "W05": (1391410800.65, 1391797033.75),
              "W06": (1392015600.01, 1392398212.78)}
week_names = sorted(week_specs.keys())
week_for_evaluation = week_names
path_user_sample=path_join("Uploads", "TrainData")
expert_data_glob_pattern = path_join("StampRally_*", "Uploads", "TrainData",        "*.json")
expert_data_test_glob_pattern = path_join("StampRally_*", "ValidationData", "*.json")
k = 50

@property
def data_set_path(self):
    return path_join(self.base_path, "SCSUT2014v1", "EXP201312")

@property
def expert_data_path(self):
    return path_join(self.base_path, "SCSUT2014v1", "TESTDATA") 

@property
def config_path(self):
    return path_join(self.data_set_path, "StampRally")

@property
def results_path(self):
    return path_join(self.base_path, "results")

@property
def rules_path(self):
    return path_join(self.results_path, 'rules')

@property
def unified_time_series_path(self):
    return path_join(self.results_path, 'timeseries') 

@property
def titarl_configs_path(self):
    return path_join(self.base_path, 'titarl_cfg')

@property
def rule_learning_template(self):
    return path_join(self.base_path, "learning_config_e0.xml")

@property
def learn_all_file(self):
    return path_join(self.base_path, "learn_all.bat")

@property
def log_path(self):
    return path_join(self.base_path, "logs")

@property
def trees_path(self):
    return path_join(self.results_path, "trees")


config = Config()

paths = []
for attrib in dir(config):
  if "_path" in attrib:
    paths.append(attrib)

for path in [config.titarl_configs_path, config.unified_time_series_path,   config.rules_path, config.trees_path]:
paths.append("%s%squarterly" % (path, path_sep))

config.paths = paths
请帮助我,我不知道错误是什么,我也在谷歌上搜索过,但没有找到解决此错误的任何方法,这是什么样的错误,我无法理解,所以请帮助我,我被困在这里,因为我对python语言非常陌生。

in:

repository = Repository(Config)
您正在传递
Config
类本身,而不是该类的实例

改为:

config = Config()
# ... set up config here ...
repository = Repository(config)
在:

您正在传递
Config
类本身,而不是该类的实例

改为:

config = Config()
# ... set up config here ...
repository = Repository(config)

test.py
文件中,尝试更改以下两行代码:

from configuration import Config
repository = Repository(Config)
像这样:

from configuration import config
repository = Repository(config)

test.py
文件中,尝试更改以下两行代码:

from configuration import Config
repository = Repository(Config)
像这样:

from configuration import config
repository = Repository(config)

@AnasReza,我已经在本地计算机上重新创建了您项目的这一部分,修复后代码不会抛出断言错误。也许还有别的例外?你能提供一个输出吗?回溯(最后一次调用):文件“D:/Py Charm projects/Example/test.Py”,第3行,在repository=repository(配置)文件“D:\Py Charm projects\Example\repository.Py”,第46行,在init m(self)文件“D:\Py Charm projects\Example\repository.Py”,第86行,在load\u expert\u data user=re.match中(“*StampRally_uuz([a-z]*)/”,dirname(f)).group(1)AttributeError:'NoneType'对象没有属性'group'。这是我在实现solution@AnasReza,正如我所想,这是完全不同的。问题是repository.py:86中的regex找不到任何出现的
*StampRally\uuz([a-z]*)/
在某个文件的目录名
f
dirname(f)
)。如果没有一个包含所有项目目录和文件的树,我认为不可能帮助您。您可以尝试用这个新问题和所有必要的信息创建另一个问题,因为
AssertionError
的问题实际上已经解决了,您离解决方案又近了一步。@AnasReza,我认为这个问题已经解决了与代码无关。可能与项目的文件有关或缺少这些文件。也可能是错误的文件/目录命名。如果没有有关此代码应执行的操作和输入数据(文件)的任何其他信息,则无法说明是否收到。@AnasReza,我已在本地计算机上重新创建了您项目的这一部分,修复后代码不会抛出断言错误。可能还有其他异常?您能否提供输出?回溯(最近一次调用):文件“D:/Py Charm projects/Example/test.Py”,第3行,在repository=repository(配置)中文件“D:\Py Charm projects\Example\repository.Py”,第46行,在init m(self)文件“D:\Py Charm projects\Example\repository.Py”的第86行,在load\u expert\u data user=re.match(“.*stampraly”([a-z]*)/”,dirname(f)).group(1)AttributeError:'NoneType'对象没有属性'group'。这是我在实现solution@AnasReza,正如我所想,这是完全不同的。问题是repository.py:86中的regex在某个文件的dirname
f
dirname(f))中找不到任何出现的
*StampRally([a-z]*)/
)。如果没有一个包含所有项目目录和文件的树,我认为不可能帮助您。您可以尝试用这个新问题和所有必要的信息创建另一个问题,因为
AssertionError
的问题实际上已经解决了,您离解决方案又近了一步。@AnasReza,我认为这个问题已经解决了与代码无关。可能与项目的文件有关或缺少这些文件。也可能是错误的文件/目录命名。如果没有有关此代码应执行的操作以及它接收的输入数据(文件)的任何其他信息,则无法说明。