Python importlib import_module 模块的相对导入

标签 python python-3.x import python-importlib

根据 this answer , 你可以使用 importlibimport_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

关于Python importlib import_module 模块的相对导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38310519/

相关文章:

python - 如何理解 Python 中的表达式列表

regex - 如何使用Python获取包含某种“href”格式的所有“a”标签?

mysql - 在 Wordpress 网站上发布 Filemaker(数据库软件)数据

java - 使用导入静态字段是一种好的编程习惯吗?

python - TensorFlow操作,在官方API中找不到

python - 属性错误 : 'Namespace' object has no attribute

python - 如何将字数列表转换为数据框以进行情感分析

python - 无模块名称,下划线导入

c++ - CLion 不支持 CSV 文件?

python - 压缩 "n"时间对象成员调用