如何修正Python代码实现剧集季数字典键按整数排序?
修正Python剧集分类排序代码:整数键排序与双文件输出
以下是修正后的完整代码,解决了字符串键排序异常、类型不匹配及键错误问题:
def process_episodes(input_filename): # 字典键为整数类型季数,值为对应剧集列表 season_episodes = {} with open(input_filename, 'r', encoding='utf-8') as f: for line in f.readlines(): line = line.strip() if not line: continue # 跳过空行 # 解析行内容,兼容"1: 剧集名"、"S2: 剧集名"、"Season 3: 剧集名"等格式 try: season_part, title = line.split(':', 1) # 提取季数中的数字并转为整数 season_num = int(''.join(filter(str.isdigit, season_part))) title = title.strip() except (ValueError, IndexError): print(f"跳过格式无效的行: {line}") continue # 填充字典 if season_num not in season_episodes: season_episodes[season_num] = [] season_episodes[season_num].append(title) # 按季数从小到大排序 sorted_seasons = sorted(season_episodes.keys()) # 生成output_keys.txt with open('output_keys.txt', 'w', encoding='utf-8') as f: for season in sorted_seasons: episodes_str = '; '.join(season_episodes[season]) f.write(f"季{season}: {episodes_str}\n") # 收集所有剧集并按字母序排序 all_titles = [] for episodes in season_episodes.values(): all_titles.extend(episodes) # 不区分大小写排序,如需严格区分大小写可移除key=str.lower sorted_titles = sorted(all_titles, key=str.lower) # 生成output_titles.txt with open('output_titles.txt', 'w', encoding='utf-8') as f: for title in sorted_titles: f.write(f"{title}\n") # 运行程序,输入目标文件名 if __name__ == "__main__": input_file = input("请输入文件名: ") process_episodes(input_file)
核心修正点
- 整数键存储:将季数转为
int类型作为字典键,从根源解决字符串排序的异常(如"10"排在"2"前的问题)。 - 鲁棒的格式解析:通过提取数字字符兼容多种季数格式,同时用
try-except捕获无效行,避免程序崩溃。 - 消除类型不匹配错误:全程使用整数键访问字典,彻底避免字符串/整数类型不一致导致的
KeyError。 - 双文件输出逻辑:
output_keys.txt:按季数升序排列,同季剧集用分号分隔;output_titles.txt:所有剧集按字母序(不区分大小写)排序输出,可根据需求调整排序规则。
内容的提问来源于stack exchange,提问作者user21922227
相关产品推荐
相关产品推荐

