AttributeError: Can’t get attribute ‘Vocabulary’ on <module ‘main’

文章描述了在迁移项目时遇到的问题,即在使用pickle.load加载.pkl文件时出现AttributeError,因为无法在main模块中找到Verbosity类。作者尝试了两种解决方案:1)直接导入所需类;2)自定义Unpickler类并重写find_class方法来定位类。第二种方法成功解决了问题。
摘要由CSDN通过智能技术生成

vocab = pickle.load(f) AttributeError: Can’t get attribute ‘Vocabulary’ on <module ‘main

为从文件中导入之前构建的.pkl词典文件,将笔记本上正常运行的项目迁移到台式机上时,vocab = pickle.load(f)发生了此报错,但是原本能正常运行,并没有找到具体原因(

对于pickle.load(f)的报错,在中文博客找到的大多数解决措施都为在此文件中import此类,但个人没有解决此问题,在python - Unable to load files using pickle and multiple modules - Stack Overflow 中找到了如下重写class CustomUnpickler.find_class()的方法。留档用。

import pickle

import class_def

if __name__=='__main__':
    with open('test_data.pkl', 'rb') as f:
        users = pickle.load(f)

运行上面的代码尝试打开pickle文件,会抛出与 # vocab = pickle.load(f) AttributeError: Can’t get attribute ‘Vocabulary’ on <module 'main’相同的错误。

方法1: 在含有pickle.load(f)的文件中引用需要的类
import pickle

import class_def
from utils.build_vocab import Vocabulary #导入Vocabulary类

if __name__=='__main__':
    with open('test_data.pkl', 'rb') as f:
        users = pickle.load(f)
方法2:重写class CustomUnpickler.find_class()
import pickle

class CustomUnpickler(pickle.Unpickler):

    def find_class(self, module, name):
        if name == 'Vocabulary':
            from settings import Vocabulary
            return Vocabulary
        return super().find_class(module, name)

pickle_data = CustomUnpickler(open('file_path.pkl', 'rb')).load()

个人在使用方法2后问题解决

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值