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

如何用Python将记事本数据转换为指定格式的Excel文件

用Python将记事本数据转换为指定格式的Excel文件

需求说明

给定记事本中的数据:node1、7、p 2、r 5、node2、6、p 2、r 4,需要生成Excel文件,要求:

  • 行索引为node1、node2
  • 列名为total、primary、replicas
  • 映射规则:纯数字对应total,p后数字对应primary,r后数字对应replicas

实现步骤与代码

1. 依赖安装

首先安装所需Python库:

pip install pandas openpyxl

2. 完整代码

import pandas as pd

# 读取记事本数据(替换为你的txt文件路径)
with open('data.txt', 'r', encoding='utf-8') as f:
    raw_items = f.read().strip().split('、')

# 初始化数据存储结构
node_records = {}
current_node = None

# 解析每一项数据
for item in raw_items:
    item = item.strip()
    if not item:
        continue
    
    # 识别节点名称
    if item.startswith('node'):
        current_node = item
        node_records[current_node] = {'total': None, 'primary': None, 'replicas': None}
    # 识别total值(纯数字)
    elif item.isdigit():
        if current_node:
            node_records[current_node]['total'] = int(item)
    # 识别primary或replicas值
    elif item.startswith(('p ', 'r ')):
        if current_node:
            prefix, value = item.split()
            if prefix == 'p':
                node_records[current_node]['primary'] = int(value)
            elif prefix == 'r':
                node_records[current_node]['replicas'] = int(value)

# 转换为DataFrame并导出Excel
df = pd.DataFrame.from_dict(node_records, orient='index')
df.index.name = 'Node'
df.to_excel('node_statistics.xlsx', engine='openpyxl')

print("Excel文件已成功生成:node_statistics.xlsx")

代码说明

  • 读取txt文件后,按、拆分所有数据项
  • 遍历过程中维护当前节点,根据项的类型(节点名/纯数字/p/r前缀)填充对应字段
  • 使用pandas.DataFrame.from_dict将字典转换为表格,orient='index'确保节点作为行索引
  • 指定engine='openpyxl'以支持.xlsx格式的Excel文件导出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 22:22:43