我使用pickle通过转储根来保存对象图。当我加载根时,它有所有的实例变量和连接的对象节点。不过,我将所有节点保存在dictionary类型的类变量中。类变量在保存前已满,但在我取消数据拾取后,它是空的。在
以下是我使用的课程:
class Page():
__crawled = {}
def __init__(self, title = '', link = '', relatedURLs = []):
self.__title = title
self.__link = link
self.__relatedURLs = relatedURLs
self.__related = []
@property
def relatedURLs(self):
return self.__relatedURLs
@property
def title(self):
return self.__title
@property
def related(self):
return self.__related
@property
def crawled(self):
return self.__crawled
def crawl(self,url):
if url not in self.__crawled:
webpage = urlopen(url).read()
patFinderTitle = re.compile('<title>(.*)</title>')
patFinderLink = re.compile('<link rel="canonical" href="([^"]*)" />')
patFinderRelated = re.compile('<li><a href="([^"]*)"')
findPatTitle = re.findall(patFinderTitle, webpage)
findPatLink = re.findall(patFinderLink, webpage)
findPatRelated = re.findall(patFinderRelated, webpage)
newPage = Page(findPatTitle,findPatLink,findPatRelated)
self.__related.append(newPage)
self.__crawled[url] = newPage
else:
self.__related.append(self.__crawled[url])
def crawlRelated(self):
for link in self.__relatedURLs:
self.crawl(link)
我是这样保存的:
^{pr2}$我是这样装的:
def loadGraph(filename): #returns root
with open(filename,'r') as inf:
return pickle.load(inf)
root = loadGraph('medTwiceGraph.dat')
除了类变量\uuu crawled之外的所有数据加载。在
我做错什么了?在
对于任何感兴趣的人,我所做的就是制作一个包含实例变量的超类图,并将我的爬行函数移动到图中。页面现在只包含描述页面及其相关页面的属性。我pickle我的Graph实例,其中包含我的所有Page实例。这是我的密码。在
默认情况下,pickle只使用
self.__dict__
的内容,而不使用您认为想要的self.__class__.__dict__
。在我说“你认为你想要什么”是因为取消一个实例不应该改变类级别的状态。在
如果你想改变这种行为,那么看看}in the docs
__getstate__
和{Python并没有真正地pickle类对象。它只是保存它们的名字和在哪里找到它们。根据^{} 的文档:
在您的示例中,您可以解决将
__crawled
更改为实例属性或全局变量的问题。在相关问题 更多 >
编程相关推荐