Skip to main content
 首页 » 编程设计

Python importlib import_module 模块的相对导入

2024年10月17日7kerrycode

根据 this answer , 你可以使用 importlib 到 import_module 使用像这样的相对导入:

importlib.import_module('.c', 'a.b') 

为什么相对导入对 sklearn.feature_extraction.text 不起作用?

importlib.import_module('.text', 'sklearn.feature_extraction') 

我验证了 text 是一个模块:

from types import ModuleType 
import sklearn.feature_extraction.text 
isinstance(sklearn.feature_extraction.text, ModuleType) 

返回

True 

编辑

“不起作用”是指它没有导入模块。

我正在使用 Python 3.4

绝对方式工作:

import importlib 
text = importlib.import_module('sklearn.feature_extraction.text') 
tfidf = text.TfidfVectorizer() 

相对方式不是:

import importlib 
text = importlib.import_module('.text', 'sklearn.feature_extraction') 
Traceback (most recent call last): 
  File "<pyshell#28>", line 1, in <module> 
    text = importlib.import_module('.text', 'sklearn.feature_extraction') 
  File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module 
    return _bootstrap._gcd_import(name[level:], package, level) 
  File "<frozen importlib._bootstrap>", line 2249, in _gcd_import 
  File "<frozen importlib._bootstrap>", line 2199, in _sanity_check 
SystemError: Parent module 'sklearn.feature_extraction' not loaded, cannot perform relative import 

请您参考如下方法:

在尝试相对导入之前需要导入父模块。

如果你想让它工作,你必须在调用 import_module 之前添加 import sklearn.feature_extraction。

这里有很好的解释:https://stackoverflow.com/a/28154841/1951430