python - 将文本文件转换为 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 表)
解决方案
正如评论中所建议的,您首先需要解析出值和列名。完成此操作后,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')
如果你有很多文件,你可以尝试将上面的解析方法包装到一个函数中并循环它们。
推荐阅读
- javascript - 日期选择器上的弹出窗口
- jquery - 将 json 数组数据从 html 发送到 Flask
- xml - 根据条件 XSLT 2.0 获取日期列表
- ionic-framework - 使用键盘后 Ionic3 标签栏不可点击
- c - 计算C中字符串中每个单词的长度的程序
- excel - 自动排序 - 停止返回表格顶部
- realm - 将 Realm GraphQL 客户端与 Realm Cloud 中的全局/共享领域一起使用
- selenium - 如何使用 xpath 选择此元素?
- css - Webpack 和 boostrap,从样式标签中删除样式
- matplotlib - pcolormesh'GeoAxesSubplot'对象的cartopy问题没有属性'_hold'