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

Python读取record.txt指定行列字符异常问题求助

问题修复:提取文件指定行列字符

问题根源

你的代码错误假设文件列是用制表符(\t)分隔,但实际文件通过多个连续空格分隔列。这导致line.strip().split("\t")将每一行内容视为单个元素:

  • 当start_column=1时,row_values[0:3]返回整行内容,表现为输出所有列;
  • 当start_column>1时,row_values[start_column-1:end_column]找不到对应下标,返回空列表。

修复方案

方案1:默认空白分割(最简适配)

Python的str.split()默认按任意数量空白字符(含多空格、制表符)分割,自动忽略首尾空白,完美适配当前文件格式:

def get_value_from_file(file_path, start_row, end_row, start_column, end_column):
    with open(file_path, "r", encoding="utf-8") as file:
        lines = file.readlines()

    selected_lines = lines[start_row-1:end_row]

    values = []
    for line in selected_lines:
        # 替换制表符分割为默认空白分割
        row_values = line.strip().split()
        # 提取指定列
        selected_cols = row_values[start_column-1:end_column]
        # 提取每个列的前3个字符,匹配预期输出
        for col in selected_cols:
            values.append(col[:3])

    return values

file_path = "record.txt"
start_row = 1
end_row = 10
start_column = 1
end_column = 3

result = get_value_from_file(file_path, start_row, end_row, start_column, end_column)
# 按预期格式逐行打印
for item in result:
    print(item)

方案2:正则精确分割(兼容列内含单个空格场景)

如果后续遇到列内容包含单个空格的情况,可用正则匹配2个及以上连续空格作为分隔符,避免误分割:

import re

def get_value_from_file(file_path, start_row, end_row, start_column, end_column):
    with open(file_path, "r", encoding="utf-8") as file:
        lines = file.readlines()

    selected_lines = lines[start_row-1:end_row]

    values = []
    for line in selected_lines:
        # 正则匹配2个及以上空格作为分隔符
        row_values = re.split(r'\s{2,}', line.strip())
        selected_cols = row_values[start_column-1:end_column]
        for col in selected_cols:
            values.append(col[:3])

    return values

# 调用逻辑同方案1

预期输出示例

运行修复后的代码会得到符合要求的结果:

Tar

202
202
202
202
202
202
202
202
202

...(共30个字符,对应10行×3列的前3位字符)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 15:57:17