Python遍历《麦克白》角色字典键调用函数仅返回首条结果求解
问题原因
common_words函数硬编码了角色名:函数内部读取台词时写死了d['macb'],无论传入什么角色参数,永远只统计麦克白的台词,导致所有角色的统计结果完全一致。- 去重逻辑误删有效数据:你在
final_common里加了if common not in group_common的判断,因为所有角色的统计结果都和第一个麦克白的结果相同,后续数据全被判定为重复丢弃,最终列表只会保留1条数据。 - 返回结构不符合要求:当前代码只存储了高频词列表,没有绑定对应角色名,和你需要的「角色名+对应高频词」的输出结构不匹配。
修复方案
第一步:修改common_words函数,替换硬编码的角色名
from collections import Counter import requests def common_words(character, filter_stop = False, stop_words = []): if filter_stop: stop_words = set(filter(None, requests.get("https://gist.githubusercontent.com/sebleier/554280/raw/7e0e4a1ce04c2bb7bd41089c9821dbcf6d0c786c/NLTK's%2520list%2520of%2520english%2520stopwords").text.split('\n'))) # 将硬编码的d['macb']替换为传入的character参数 w = [i for _, b in d[character] for i in re.sub('[\:\.\?]+', '', b).split() if i.lower() not in stop_words] return Counter(w).most_common(5)
第二步:修改final_common函数,调整返回结构、移除冗余去重逻辑
def final_common(character_list): group_common = [] for name in character_list: # 可根据需求调整filter_stop参数是否开启停用词过滤 common = common_words(name, filter_stop=True) # 存储结构调整为(角色名, 高频词列表),匹配输出要求 group_common.append((name, common)) return group_common # 调用测试 names = d.keys() result = final_common(names) for name, words in result: print(f"'{name}', {words}")
如果确实需要过滤掉高频词完全相同的角色,可以保留原来的去重判断,只需要调整判断逻辑为判断(name, common)是否重复即可。
内容的提问来源于stack exchange,提问作者zelfde
相关产品推荐
相关产品推荐

