gpt4 book ai didi

Python importlib import_module 模块的相对导入

转载 作者:太空宇宙 更新时间:2023-11-04 03:10:07 26 4
gpt4 key购买 nike

根据 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com