如何在setuptools中替代symspellpy已弃用的pkg_resources.resource_filename访问资源
替代symspellpy中已弃用的pkg_resources.resource_filename方法
pkg_resources.resource_filename属于setuptools模块,目前已被官方弃用,标准库的importlib.resources是当前首选的资源访问方案,以下是针对symspellpy词典文件的替代实现:
Python 3.9+ 推荐写法
直接使用importlib.resources.files获取包资源路径,返回的Path对象可直接转换为字符串供symspellpy使用:
from importlib.resources import files import symspellpy from symspellpy import SymSpell # 获取词典文件的Path对象 dictionary_path = files(symspellpy).joinpath("frequency_dictionary_en_82_765.txt") bigram_path = files(symspellpy).joinpath("frequency_bigramdictionary_en_243_342.txt") # 初始化SymSpell并加载词典 sym_spell = SymSpell(max_dictionary_edit_distance=2, prefix_length=7) sym_spell.load_dictionary(str(dictionary_path), term_index=0, count_index=1) sym_spell.load_bigram_dictionary(str(bigram_path), term_index=0, count_index=2)
Python 3.8及以下兼容写法
低版本Python需使用importlib.resources.path配合上下文管理器获取路径:
from importlib.resources import path import symspellpy from symspellpy import SymSpell sym_spell = SymSpell(max_dictionary_edit_distance=2, prefix_length=7) # 加载单词语典 with path(symspellpy, "frequency_dictionary_en_82_765.txt") as dictionary_path: sym_spell.load_dictionary(str(dictionary_path), term_index=0, count_index=1) # 加载双词语典 with path(symspellpy, "frequency_bigramdictionary_en_243_342.txt") as bigram_path: sym_spell.load_bigram_dictionary(str(bigram_path), term_index=0, count_index=2)
关键说明
importlib.resources是Python标准库模块,无需额外安装依赖- 返回的
Path对象支持所有文件路径操作,转换为字符串即可适配symspellpy的API - 避免了
pkg_resources带来的性能开销和弃用警告
内容的提问来源于stack exchange,提问作者Francis Smart
相关产品推荐
相关产品推荐

