使用Pandas将文本文件按字段名转为列并生成Excel表格
需要将以下格式的文本文件:
Tag: liprod_Liosprod8_LIOS_12.3_NIGHT_linux8_hudson
Global path: /net/liosprod8.cvc-global.net/export/viewstore/liprod/liprod_Liosprod8_LIOS_12.3_NIGHT_linux8_hudson.vws
Server host: liosprod8.cvc-global.net
Region: cssall
Active: NO
View tag uuid:ccd335a4.fb8011eb.af37.00:50:56:bf:58:95
View on host: liosprod8.cvc-global.net
View server access path: /export/viewstore/liprod/liprod_Liosprod8_LIOS_12.3_NIGHT_linux8_hudson.vws
View uuid: ccd335a4.fb8011eb.af37.00:50:56:bf:58:95
View attributes: snapshot
View owner: tmn/liprodTag: liprod_Liosprod8_LIOS_DF3_NIGHT_linux8_hudson
Global path: /net/liosprod8.cvc-global.net/export/viewstore/liprod/liprod_Liosprod8_LIOS_DF3_NIGHT_linux8_hudson.vws
Server host: liosprod8.cvc-global.net
Region: cssall
Active: NO
View tag uuid:dc2ff6f7.fb8311eb.bb47.00:50:56:bf:58:95
View on host: liosprod8.cvc-global.net
View server access path: /export/viewstore/liprod/liprod_Liosprod8_LIOS_DF3_NIGHT_linux8_hudson.vws
View uuid: dc2ff6f7.fb8311eb.bb47.00:50:56:bf:58:95
View attributes: snapshot
View owner: tmn/liprod
转换为Excel表格,要求每个Tag对应一行,所有字段映射到对应列。以下是基于Pandas的实现方案:
Pandas 实现脚本
import pandas as pd # 定义字段与Excel列名的映射关系 field_mapping = { 'Tag': 'Tag', 'Global path': 'GlobalPath', 'Server host': 'ServerHost', 'Region': 'Region', 'Active': 'Active', 'View tag uuid': 'ViewTagUUID', 'View on host': 'ViewOnHost', 'View server access path': 'ViewServerAccessPath', 'View uuid': 'ViewUUID', 'View attributes': 'ViewAttributes', 'View owner': 'ViewOwner' } # 读取文本文件并清理空行 with open('your_file.txt', 'r') as f: lines = [line.strip() for line in f if line.strip()] data_list = [] current_entry = {} for line in lines: # 处理两种冒号分隔情况:带空格和不带空格 if ': ' in line: key, value = line.split(': ', 1) else: key, value = line.split(':', 1) key = key.strip() value = value.strip() # 遇到新Tag时,保存当前条目并初始化新条目 if key == 'Tag': if current_entry: data_list.append(current_entry) current_entry = {field_mapping[key]: value} else: if key in field_mapping: current_entry[field_mapping[key]] = value # 加入最后一条未保存的条目 if current_entry: data_list.append(current_entry) # 生成DataFrame并导出为Excel df = pd.DataFrame(data_list) df.to_excel('view_data.xlsx', index=False)
原脚本排查方向
如果原有脚本未得到预期结果,可从以下几点排查:
- 文本分割逻辑:检查是否处理了
View tag uuid:xxx这种冒号后无空格的情况,避免分割错误导致字段值提取失败。 - 新Tag判断逻辑:确认每次遇到
Tag:时,是否正确保存上一条数据并初始化新条目,防止多条数据合并到同一行。 - 字段映射完整性:检查所有字段是否都被正确映射到目标列,是否有遗漏的字段未被提取。
- 空行处理:确认是否跳过了文本中的空行,避免空行干扰数据解析流程。
内容的提问来源于stack exchange,提问作者Champs

