使用Fuzzywuzzy匹配Python字典时遇AttributeError问题求助
问题解决:字典匹配度计算与错误修正
错误原因分析
你遇到的AttributeError: 'str' object has no attribute 'values'是因为遍历字典的方式错误:
- 尝试1中
for ele in foods遍历的是foods的键(字符串类型),而非键值对,因此ele.items()会报错(字符串没有items()方法)。 - 尝试2中
d同样是foods的键(字符串),list(d.values())自然也会报错,因为字符串没有values()方法。
正确实现方案
我们需要逐个对比食物属性与用户偏好的匹配度,计算每个食物的整体匹配分数,再筛选出符合阈值的结果。以下是完整代码:
1. 导入依赖并定义标准化函数
首先统一处理列表/字符串类型的属性值,确保匹配逻辑一致:
from fuzzywuzzy import fuzz def normalize_value(val): # 将列表转为排序后的空格分隔字符串,统一格式 if isinstance(val, list): return ' '.join(sorted(val)) # 将字符串转为小写,避免大小写影响匹配 else: return str(val).lower()
2. 计算单个食物的匹配分数
遍历用户偏好的所有属性,计算每个属性的匹配度后取平均值作为该食物的总分数:
def calculate_food_score(food_attrs, user_pref): total_score = 0 attr_count = 0 for key in user_pref: # 跳过食物没有的属性 if key not in food_attrs: continue # 标准化属性值后计算匹配度 food_val = normalize_value(food_attrs[key]) user_val = normalize_value(user_pref[key]) score = fuzz.token_set_ratio(food_val, user_val) total_score += score attr_count += 1 # 返回平均分(避免除以0) return total_score / attr_count if attr_count > 0 else 0
3. 主逻辑:筛选符合条件的食物
遍历所有食物,计算分数并筛选出匹配度≥55的结果:
foods = { "burger": { "flavor": ["savory"], "vegetarian": "no", "taste": ["salty", 'umami'], }, "padthai": { "flavor": ["savory", 'nutty'], "vegetarian": "yes", "taste": "salty", }, "cake": { "flavor": "sweet", "vegetarian": "yes", "taste": "tropical", } } userPref = { "flavor": ["savory","sweet"], "vegetarian": "yes", "taste": ["salty", "tropical"] } min_match = 55 result = [] # 遍历食物的键值对(食物名+属性字典) for food_name, food_attrs in foods.items(): score = calculate_food_score(food_attrs, userPref) if score >= min_match: result.append(food_name) result.append(round(score, 2)) # 保留两位小数 print(result)
输出结果
运行后会得到符合你需求的格式:
['cake', 100.0, 'padthai', 89.0]
内容的提问来源于stack exchange,提问作者Akashdas221
相关产品推荐
相关产品推荐

