从子子文件夹导入模块的问题

问题描述 投票:1回答:1

我正在尝试使用uncertainty库,我已经克隆了我的目录结构中的repo,如下所示:

.Lux/
├── generateFeatures.py
├── generateLexicons.py
├── __init__.py
├── res
│   ├── __init__.py
│   ├── test2.py
│   └── uncertainty
│       ├── __init__.py
│       ├── test1.py
│       └── uncertainty
│           ├── classifier.py
│           ├── lib
│           │   ├── __init.py__
│           │   └── nlp
│           │       ├── __init__.py

我的两个test.py有相似的内容,他们尝试做的就是导入不确定性分类器

test1.py完美无瑕

from uncertainty.classifier import Classifier

但是test2.py

from uncertainty.uncertainty.classifier import Classifier

收益率:

Traceback (most recent call last):
  File "/home/lucas/Lux/Lux/lib/python3.5/site-packages/pkg_resources/__init__.py", line 359, in get_provider
    module = sys.modules[moduleOrReq]
KeyError: 'uncertainty.lib.nlp'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    from uncertainty.uncertainty.classifier import Classifier
  File "/home/lucas/Lux/res/uncertainty/uncertainty/classifier.py", line 9, in <module>
    from .lib.nlp import summarizer
  File "/home/lucas/Lux/res/uncertainty/uncertainty/lib/nlp/__init__.py", line 3, in <module>
    VERBS_PATH = resource_filename('uncertainty.lib.nlp', 'verbs.txt')
  File "/home/lucas/Lux/Lux/lib/python3.5/site-packages/pkg_resources/__init__.py", line 1144, in resource_filename
    return get_provider(package_or_requirement).get_resource_filename(
  File "/home/lucas/Lux/Lux/lib/python3.5/site-packages/pkg_resources/__init__.py", line 361, in get_provider
    __import__(moduleOrReq)
ImportError: No module named 'uncertainty.lib'

为什么test1.py工作,test2.py不?

更新

我已经在没有它们的每个文件夹上放置了空的__init__.py,但仍然无法解决这个问题。

我已经尝试将我的外部uncertainty文件夹重命名为其他人认为它可能是一个糟糕的解析名称,但这也无效。

python python-3.x
1个回答
0
投票

问题是由于__init__.py文件夹中的lib/nlp文件而发生的。正如thom747在评论中指出的那样,VERBS_PATHverbs'txt中的uncertainty/lib/nlp提供了一条路径。

test1.py导入时,此路径是正确的,但在从test2.py导入时,它会在父lib/nlp目录中查找uncertainty,其中存在test2.py文件。它找不到一个,因此你得到一个ImportError

固定

只需将VERBS_PATH文件中的uncertainty/lib/nlp/__init__.py赋值更改为

VERBS_PATH = resource_filename('uncertainty.uncertainty.lib.nlp', 'verbs.txt')
© www.soinside.com 2019 - 2024. All rights reserved.