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后问题解决

Logo

鸿蒙生态一站式服务平台。

更多推荐