如何用Python函数实现社交关系数据的格式化输出?
Python 文本文件社交关系格式化输出修正方案
原始输入文件(nw_data1.txt)
10 Robert Jack Robert Gary Lizzie Dave Lena Mia Dave Mia Caroline Rafael Robert Nick
目标输出格式
Robert -> Jack, Gary, Nick Jack -> Robert Gary -> Robert Lizzie -> Dave Dave -> Lizzie, Mia Mia -> Dave, Caroline Caroline -> Mia Lena -> Rafael ->
原代码问题分析
- 未初始化
friends字典,直接使用会触发报错 Social_NW=[file.read()]将整个文件内容作为单个字符串存入列表,无法按行处理每条关系- 错误通过
name[0]、name[1]取字符串字符,而非分割后的名字字段 - 未处理双向好友关系(比如Robert和Jack需互相添加到对方好友列表)
- 循环逻辑混乱,提前
break导致仅处理了一条数据 - 未处理单名字行(如Lena、Rafael)的情况
修正后的完整代码
def load_social_network(file_path): friends = {} with open(file_path, "r") as file: # 跳过第一行的行数统计标记 next(file) for line in file: # 去除首尾空白,按任意空白分割名字 names = line.strip().split() if len(names) < 2: # 仅单个名字时,初始化空好友列表 name = names[0] if name not in friends: friends[name] = [] continue # 处理双向好友关系 name1, name2 = names[0], names[1] # 给name1添加好友name2 if name1 not in friends: friends[name1] = [] if name2 not in friends[name1]: friends[name1].append(name2) # 给name2添加好友name1 if name2 not in friends: friends[name2] = [] if name1 not in friends[name2]: friends[name2].append(name1) return friends def format_output(friends_dict): # 计算最长名字长度,实现输出对齐 max_name_len = max(len(name) for name in friends_dict.keys()) for name in sorted(friends_dict.keys()): friends_str = ", ".join(friends_dict[name]) # 左对齐名字,统一宽度输出 print(f"{name.ljust(max_name_len)} -> {friends_str}") while True: cus_inp = input("Type what file you would like to open? = ") if cus_inp == "nw_data1.txt": display_input = input("Would you like to see the network? Y/N: ").strip().upper() while True: if display_input == "Y": social_network = load_social_network(cus_inp) format_output(social_network) break elif display_input == "N": print("Program has been closed. Thank you for your time.") exit() else: print("Wrong input, please use Y/N.") display_input = input("Would you like to see the network? Y/N: ").strip().upper() else: print(f"File {cus_inp} not found. Please enter nw_data1.txt.")
代码说明
load_social_network函数:- 初始化空字典存储好友关系
- 跳过文件第一行的行数标记(原始文件第一行的
10为行数统计) - 逐行处理文件内容,分割并清洗名字字段
- 单名字行仅初始化空好友列表,双名字行添加双向好友关系,避免重复
format_output函数:- 计算最长名字长度保证输出对齐
- 按名字排序后,格式化输出为要求的
名字 -> 好友列表形式
- 交互逻辑:
- 统一将输入转为大写,避免大小写判断误差
- 增加文件不存在的提示,优化流程逻辑
内容的提问来源于stack exchange,提问作者Piotr Telok
相关产品推荐
相关产品推荐

