You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现TXT文件行枚举及指定列值求和问题求助

问题描述

我是Python新手,尝试读取Windows/Mac系统下的Your_Wordle_Results.txt文件,想要对1pt列的4、1、4三个数值求和,但当前代码未正确遍历目标行,导致结果为4×3。请求添加枚举类功能以实现正确求和。

原代码

import os
import platform

pathwindows = os.environ['USERPROFILE'] + r"\Documents\Your_Wordle_Results.txt"
pathmac = r'/Mac/Users/%USEPROFILE%/Documents/Your_Wordle_Results.txt'
isFileWindows = os.path.exists(pathwindows)
isFileMac = os.path.isfile(pathmac)

if isFileWindows == True:
    outfile = open(pathwindows, 'r')

if isFileMac == True:
    outfile = open(pathmac, 'r')

totalpoints1 = 0
totalpoints2 = 0
totalpoints3 = 0
totalpoints4 = 0
totalpoints5 = 0

with open(pathwindows, 'r') as fp:
    lineofinterest = fp.readlines()[2:100]
    stringlineofinterest = str(lineofinterest)
    print(*lineofinterest)
    for line in lineofinterest:
        print(line.strip())

    startline = 22
    separation = 4
    value1 = (stringlineofinterest[startline + separation * 0])
    value2 = (stringlineofinterest[startline + separation * 1])
    value3 = (stringlineofinterest[startline + separation * 2])
    value4 = (stringlineofinterest[startline + separation * 3])
    value5 = (stringlineofinterest[startline + separation * 4])

outfile.close   

print(value1)

print(totalpoints1)

TXT文件内容

Ben        Jackson    
                    1pt 2pt 3pt 4pt 5pt                    Total Results Will Be Shown Below
                    4   3   0   1   0   LOSS for audio in 7.28s
                    1   2   0   2   0   LOSS for audit in 6.18s
                    4   5   0   1   0   LOSS for audio in 7.28s
解决方案

修复后的代码

import os
from enum import Enum

# 用枚举类定义各分数列的索引,提升代码可读性和可维护性
class PointsColumn(Enum):
    PT1 = 0  # 1pt列对应的索引
    PT2 = 1
    PT3 = 2
    PT4 = 3
    PT5 = 4

# 处理跨平台文件路径
def get_file_path():
    if os.name == 'nt':  # Windows系统
        return os.path.join(os.environ['USERPROFILE'], 'Documents', 'Your_Wordle_Results.txt')
    else:  # Mac/Linux系统
        return os.path.join(os.environ['HOME'], 'Documents', 'Your_Wordle_Results.txt')

file_path = get_file_path()

total_points = {col: 0 for col in PointsColumn}

# 读取文件并计算各列总和
with open(file_path, 'r') as fp:
    lines = fp.readlines()
    # 从第3行开始读取有效数据行(索引从0开始,跳过前两行)
    data_lines = lines[2:]
    for line in data_lines:
        # 分割行内容,过滤空字符串,提取数值部分
        parts = list(filter(None, line.strip().split()))
        if len(parts) >= 5:  # 确保有足够的数值列
            # 累加1pt列的数值
            total_points[PointsColumn.PT1] += int(parts[PointsColumn.PT1.value])
            # 其他列如果需要也可以累加
            total_points[PointsColumn.PT2] += int(parts[PointsColumn.PT2.value])
            total_points[PointsColumn.PT3] += int(parts[PointsColumn.PT3.value])
            total_points[PointsColumn.PT4] += int(parts[PointsColumn.PT4.value])
            total_points[PointsColumn.PT5] += int(parts[PointsColumn.PT5.value])

# 输出1pt列的总和
print(f"1pt列总和: {total_points[PointsColumn.PT1]}")
# 其他列总和也可以按需输出
# print(f"2pt列总和: {total_points[PointsColumn.PT2]}")

关键改进说明

  1. 枚举类的使用:通过PointsColumn枚举定义各分数列的索引,避免硬编码数字,后续修改列顺序时只需调整枚举值即可,大幅提升代码可维护性。
  2. 跨平台路径处理:用os.name判断系统类型,结合os.path.join生成标准路径,同时修正了原Mac路径的错误(原代码错误使用%USEPROFILE%,改为os.environ['HOME']获取用户目录)。
  3. 正确的行遍历与数值提取:放弃原代码中硬索引取字符的错误方式,通过分割每行内容提取有效数值,遍历所有数据行累加对应列的数值,确保求和结果正确。
  4. 文件资源管理:统一使用with语句处理文件,自动关闭文件,避免资源泄漏问题。

内容的提问来源于stack exchange,提问作者Ben Jackson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 21:45:35