我有点困惑。我正在处理一个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,顺便说一下。