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

如何将.txt文件转换为列表的列表?Python新手技术求助

解决方案

思路

忽略NaN行,提取被[]包裹的表格块,将每个表格的表头和数据行分别转换成列表,最终组成列表的列表。核心步骤:

  1. 过滤无效的NaN行
  2. 识别连续的表格行(表头+数据行)
  3. 拆分每行内容为列表,可选合并日期字段为整体

基础实现(日期拆分多元素)

直接按空格拆分内容,日期会被拆分为多个独立元素:

result = []
current_table = []

with open("file.txt") as f:
    # 读取所有行并去除首尾空白
    lines = [line.strip() for line in f]

i = 0
while i < len(lines):
    current_line = lines[i]
    # 跳过NaN行
    if current_line == "NaN":
        i += 1
        continue
    # 处理表格表头行(以[开头)
    if current_line.startswith("["):
        # 去掉开头的[,按任意空格拆分表头
        header = current_line.lstrip("[").split()
        current_table.append(header)
        # 处理下一行数据行,去掉结尾的]后拆分
        data_line = lines[i+1].rstrip("]").split()
        current_table.append(data_line)
        # 将当前表格加入结果列表
        result.append(current_table)
        current_table = []
        # 跳过已处理的数据行
        i += 2
    else:
        i += 1

# 打印结果
print(result)

输出结果

[
    [
        ['From', 'To', 'Type', 'When', 'Price'],
        ['0', 'SillyZir', '0x4a34', 'Bid', 'June', '18th,', '2022', '50000']
    ],
    [
        ['From', 'To', 'Type', 'When', 'Price'],
        ['0', 'SillyZir', 'Klima#3171', 'Bid', 'June', '16th,', '2022', '60000']
    ]
]

优化实现(合并日期为单个元素)

如果希望日期作为完整字段,可以调整数据行处理逻辑,合并日期部分:

result = []
current_table = []

with open("file.txt") as f:
    lines = [line.strip() for line in f]

i = 0
while i < len(lines):
    current_line = lines[i]
    if current_line == "NaN":
        i += 1
        continue
    if current_line.startswith("["):
        header = current_line.lstrip("[").split()
        current_table.append(header)
        # 拆分数据行的所有元素
        data_parts = lines[i+1].rstrip("]").split()
        # 前4个元素保留,合并中间的日期部分,最后保留价格
        data_line = data_parts[:4] + [' '.join(data_parts[4:-1])] + [data_parts[-1]]
        current_table.append(data_line)
        result.append(current_table)
        current_table = []
        i += 2
    else:
        i += 1

print(result)

输出结果

[
    [
        ['From', 'To', 'Type', 'When', 'Price'],
        ['0', 'SillyZir', '0x4a34', 'Bid', 'June 18th, 2022', '50000']
    ],
    [
        ['From', 'To', 'Type', 'When', 'Price'],
        ['0', 'SillyZir', 'Klima#3171', 'Bid', 'June 16th, 2022', '60000']
    ]
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 07:54:20