使用enchant模块DictWithPWL时触发AttributeError的原因及解决
解决
AttributeError: module 'enchant' has no attribute 'DictWithPWL'问题 问题原因
你遇到的错误大概率是两个原因之一:
- 安装的是同名第三方
enchant包,而非官方pyenchant库 pyenchant版本差异导致DictWithPWL的调用方式变化
解决方案1:安装正确的pyenchant包
先卸载现有错误的enchant包,重新安装官方pyenchant:
pip uninstall enchant -y pip install pyenchant
重新运行原代码,若仍有问题,尝试以下替代写法:
解决方案2:调整代码调用方式
如果DictWithPWL仍无法调用,可拆分系统词典与个人词列表的检查逻辑:
import enchant def dictionary_words_finder(word_lst): meaningful_word = [] # 初始化系统英文词典 eng_dictionary = enchant.request_dict("en_US") # 加载个人词列表文件 personal_dict = enchant.PyPWL('words.txt') for word in word_lst: # 同时检查系统词典和个人词列表 if eng_dictionary.check(word) or personal_dict.check(word): meaningful_word.append(word) return meaningful_word
替代方案:不使用pyenchant的实现方式
如果上述方法仍无效,可改用以下两种方式实现需求:
方式1:使用nltk词典
import nltk from nltk.corpus import words # 首次运行需要下载词典库 nltk.download('words') def dictionary_words_finder(word_lst): # 加载系统词典 system_words = set(words.words()) # 加载个人词列表 with open('words.txt', 'r', encoding='utf-8') as f: personal_words = set(line.strip().lower() for line in f if line.strip()) # 合并词典并过滤单词 valid_words = system_words.union(personal_words) return [word for word in word_lst if word.lower() in valid_words]
方式2:纯文件读取实现
def dictionary_words_finder(word_lst): # 加载系统词典(需自行下载合适的英文词典文件,比如webster.txt) with open('webster.txt', 'r', encoding='utf-8') as f: system_words = set(line.strip().lower() for line in f if line.strip()) # 加载个人词列表 with open('words.txt', 'r', encoding='utf-8') as f: personal_words = set(line.strip().lower() for line in f if line.strip()) valid_words = system_words.union(personal_words) return [word for word in word_lst if word.lower() in valid_words]
内容的提问来源于stack exchange,提问作者code-switch
相关产品推荐
相关产品推荐

