如何为WordHoard内存缓存字典扩展无重复值的内容
问题解决:修正WordHoard缓存字典的格式错误
问题分析
你的代码当前存在两个核心问题:
- 扩展缓存时,错误地将新定义直接添加到了外层列表(
['noun', [...]]这个列表),而非内层的定义列表([...]部分),导致字典结构混乱。 - 未处理
values参数为单个字符串的情况,直接转集合会把字符串拆分为单个字符,引发逻辑错误。
修正后的代码
from typing import Dict, Tuple, Optional, Union, List temporary_dict_definition: Dict[str, List[Union[str, List[str]]]] = {} def cache_definition(word: str) -> Tuple[bool, Optional[List[Union[str, List[str]]]]]: try: values = temporary_dict_definition[word] except KeyError: return False, None else: return True, values def insert_word_cache_definition(word: str, pos_category: str, values: Union[str, List[str]]) -> None: # 统一处理values为列表格式,避免单个字符串转集合时拆分为字符 if isinstance(values, str): values = [values] if word in temporary_dict_definition: existing_pos, existing_defs = temporary_dict_definition[word] if existing_pos == pos_category: # 计算去重后的新定义,对比内层的定义列表 deduplicated_values = set(values) - set(existing_defs) # 向内层定义列表添加新值,而非外层列表 existing_defs.extend(deduplicated_values) else: # 首次插入时确保values是列表格式 temporary_dict_definition[word] = [pos_category, values if isinstance(values, list) else [values]]
关键修改说明
- 类型注解修正:将
temporary_dict_definition的类型改为Dict[str, List[Union[str, List[str]]]],匹配实际存储的结构(外层列表第一个元素是词性字符串,第二个是定义列表)。 - 统一values格式:先判断
values是否为字符串,转成列表后再处理,避免单个字符串转集合时被拆分为字符。 - 定位内层列表扩展:通过
existing_defs = temporary_dict_definition[word][1]获取内层定义列表,直接对其执行extend操作,确保新定义被添加到正确的位置。 - 首次插入的格式统一:首次插入时也确保定义部分是列表格式,避免后续处理异常。
验证效果
执行修正后的代码后,插入多个定义会得到你期望的格式:
{'mother': ['noun', ["a person's own mother", 'a female parent', 'a woman who has given birth to a child (also used as a term of address to your mother).', 'female person who has borne children']]}
内容的提问来源于stack exchange,提问作者Life is complex
相关产品推荐
相关产品推荐

