求Python脚本处理CSV文件 拆分姓名年龄并按身高分类输出新CSV
Python 处理脚本
注意:原始数据末尾的数值为身高英寸单位,需除以12转换为英尺后匹配分类规则,和给出的分类规则完全适配。你提到的“年龄存储在同一列”为笔误,实际该列对应身高数值。
import csv def get_height_class(height_inch): # 英寸转英尺 height_feet = height_inch / 12 if height_feet < 5: return "short" elif 5 <= height_feet <= 6: return "medium" else: return "tall" if __name__ == "__main__": result_list = [] # 读取原始文件 with open("input.csv", "r", encoding="utf-8") as input_file: for line in input_file: strip_line = line.strip() # 跳过空行 if not strip_line: continue # 按任意空白字符拆分内容 line_parts = strip_line.split() # 拼接全名 full_name = f"{line_parts[0]} {line_parts[1]}" # 读取身高数值 height = int(line_parts[-1]) # 获取分类 height_class = get_height_class(height) result_list.append({ "Names": full_name, "Classification": height_class }) # 写入结果文件 with open("output.csv", "w", newline="", encoding="utf-8") as output_file: csv_writer = csv.DictWriter(output_file, fieldnames=["Names", "Classification"]) csv_writer.writeheader() csv_writer.writerows(result_list)
使用说明
- 把你手里的原始文本数据保存为
input.csv,放在和脚本相同的文件夹下 - 直接用Python3运行脚本即可,不需要额外安装第三方依赖
- 运行完成后生成的
output.csv就是符合要求的目标文件
内容的提问来源于stack exchange,提问作者DairyKidd
相关产品推荐
相关产品推荐

