首页 > 解决方案 > 将文本文件转换为 Excel 表格

问题描述

需要有关如何将 txt 文件中的多行转换为 excel 表格格式的帮助

Input (txt file)
ManagedElement=BSB13,BscFunction=1,BscM=1,GeranCellM=1,GeranCell=G59218,PowerControl=1,PowerControlDownlink=1
bsPwr : 43
bsPwrBDec : 430
bsPwrMin : -20
bsPwrTDec : 430
bsRPwrOffset : 16
bsTxPwr : 43
dBtsPcState : INACTIVE
dlPcE : INACTIVE
dlPcE2a : INACTIVE
dlPcG : INACTIVE
dtxD : ON
initDlPcE : 0

输出(Excel 表)

1

标签: python

解决方案


正如评论中所建议的,您首先需要解析出值和列名。完成此操作后,pandas如有必要,您可以使用该库进行额外的数据处理。

下面的示例假设您已经阅读了文本文件,如下所示text

import pandas as pd

text = '''ManagedElement=BSB13,BscFunction=1,BscM=1,GeranCellM=1,GeranCell=G59218,PowerControl=1,PowerControlDownlink=1
bsPwr : 43
bsPwrBDec : 430
bsPwrMin : -20
bsPwrTDec : 430
bsRPwrOffset : 16
bsTxPwr : 43
dBtsPcState : INACTIVE
dlPcE : INACTIVE
dlPcE2a : INACTIVE
dlPcG : INACTIVE
dtxD : ON
initDlPcE : 0'''

lines = text.split('\n')

first_line = lines[0]
first_line_headers = [i.split('=')[0] for i in first_line.split(',')]
first_line_values = [i.split('=')[1] for i in first_line.split(',')]

other_lines = lines[1:]
other_lines_headers = [i.split(':')[0].strip() for i in other_lines]
other_lines_values = [i.split(':')[1].strip() for i in other_lines]

headers = first_line_headers + other_lines_headers
values = first_line_values + other_lines_values

df = pd.DataFrame([values], columns = headers)
df.to_excel('output.xlsx')

如果你有很多文件,你可以尝试将上面的解析方法包装到一个函数中并循环它们。


推荐阅读