You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 13:45:23