如何用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
相关产品推荐
相关产品推荐

