2

我有点困惑。我正在开发一个 Python 项目,在该项目中加载资源文件,将其作为 tsv 读取并将其转换为以模式对象为键的字典,以供以后使用。为了加载文件,到目前为止,我使用了 setuptools 中的 pkg_resources 包。它基本上看起来像这样:

from csv import DictReader
from pkg_resources import resource_string

def make_dict():
    """Make global dictionary."""
    global event_dict
    dictlines = [l.decode('utf8') for l in resource_string(
            'pkgname.resources.tsv', 'event_dict.tsv').splitlines()]
    reader = DictReader(dictlines, dialect='excel-tab')
    for row in reader:
        event = re.compile(r'\b{}\b'.format(re.escape(row['word'])))
        classes = string_to_list(row['id'])
        event_dict[event] = classes

到目前为止,它运作良好。但是,一旦我开始从另一个模块调用该模块,就会出现以下错误:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
C:\Python\Python36\lib\site-packages\pkg_resources\__init__.py in get_provider(moduleOrReq)
    430     try:
--> 431         module = sys.modules[moduleOrReq]
    432     except KeyError:

KeyError: 'pkgname.resources.tsv'

During handling of the above exception, another exception occurred:

ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-22-efa35954c76f> in <module>()
----> 1 make_event_dict()

<ipython-input-21-b318bc78e8fd> in make_event_dict()
      4     global event_dict
      5     dictlines = [l.decode('utf8') for l in resource_string(
----> 6             'pkgname.resources.tsv', 'event_classes_dict.tsv').splitlines()]
      7     reader = DictReader(dictlines, dialect='excel-tab')
      8     for row in reader:

C:\Python\Python36\lib\site-packages\pkg_resources\__init__.py in resource_string(self, package_or_requirement, resource_name)
   1215     def resource_string(self, package_or_requirement, resource_name):
   1216         """Return specified resource as a string"""
-> 1217         return get_provider(package_or_requirement).get_resource_string(
   1218             self, resource_name
   1219         )

C:\Python\Python36\lib\site-packages\pkg_resources\__init__.py in get_provider(moduleOrReq)
    431         module = sys.modules[moduleOrReq]
    432     except KeyError:
--> 433         __import__(moduleOrReq)
    434         module = sys.modules[moduleOrReq]
    435     loader = getattr(module, '__loader__', None)

ModuleNotFoundError: No module named 'pkgname'

现在我猜我的项目设置有问题,所以它的结构是这样的:

|Pkg\
|----setup.py
|----pkg\
|--------__init__.py
|--------events.py
|--------resources\
|------------__init__.py
|------------tsv\
|----------------__init__.py
|----------------event_dict.tsv

有什么问题?顺便说一句,不确定是否需要子文件夹中的 __init__.py。

4

0 回答 0