如何用Python的split函数拆分文本文件生成指定统计列表?
基于Python split函数处理选项统计文本
输入示例
3 Day 1 Option A, 30 Option B, 60 Option C, 90 Day 2 Option A, 16 Option B, 24 Option C, 30 Day 3 Option A, 64 Option B, 49 Option C, 39
期望输出
List A = [3] #total options available List B = [110, 133, 159] #sums of each individual option List C = [1, 2, 3] #number of days Option A = 110 Option B = 133 Option C = 159
用户尝试的错误代码
option_num_list = [] total_list =[] input_file = open(userfile, "r") for next_line in input_file: x = next_line.strip().split(",") option_number = x[0] option_num_list.append(option_number) total = x[-1] total_list.append(total) print(sum(total_list))
正确实现代码
# 初始化存储变量 option_sums = {} day_numbers = [] total_options = 0 # 读取并预处理文件内容 with open("input.txt", "r") as input_file: # 过滤空行并去除每行首尾空格 lines = [line.strip() for line in input_file if line.strip()] # 提取第一行的总选项数 total_options = int(lines[0]) # 遍历解析剩余行 for line in lines[1:]: if line.startswith("Day"): # 用split分割Day行,提取天数并转整数 day = int(line.split()[1]) day_numbers.append(day) else: # 按", "分割选项名和数值,处理后累加 option, value_str = line.split(", ") value = int(value_str) if option in option_sums: option_sums[option] += value else: option_sums[option] = value # 按要求格式输出结果 option_sum_list = list(option_sums.values()) print(f"List A = [{total_options}] #total options available") print(f"List B = {option_sum_list} #sums of each individual option") print(f"List C = {day_numbers} #number of days") for opt, total in option_sums.items(): print(f"{opt} = {total}")
代码说明
- 预处理数据:先过滤空行并去除每行首尾空格,避免无效数据干扰后续解析。
- 提取总选项数:直接读取第一行内容并转为整数,对应输出中的List A。
- 分类解析行数据:
- 遇到
Day开头的行,用split()分割字符串,取第二个元素作为天数存入列表,对应List C。 - 遇到选项行,用
split(", ")精准分割选项名和数值,将数值转为整数后累加对应选项的总和。
- 遇到
- 格式化输出:按需求整理统计结果,分别打印各个列表和选项的总数值。
内容的提问来源于stack exchange,提问作者user20410410
相关产品推荐
相关产品推荐

