使用huawei-lte-api读取华为Modem短信后,如何将结果整理为表格形式?
短信数据转表格的实现方案
方案1:生成Markdown格式表格(适合展示/导出)
直接提取短信数据拼接成标准Markdown表格,可直接用于文档或Markdown编辑器展示。
from huawei_lte_api.Client import Client from huawei_lte_api.Connection import Connection with Connection('http://admin:admin@192.168.8.1/') as connection: client = Client(connection) sms_list = client.sms.get_sms_list() # 提取短信列表 messages = sms_list['Messages']['Message'] if not messages: print("无短信数据") exit() # 获取表头(取第一条短信的字段作为列名) headers = list(messages[0].keys()) # 构建Markdown表格 md_table = f"| {' | '.join(headers)} |\n" md_table += f"| {' | '.join(['---']*len(headers))} |\n" # 填充每条短信数据 for msg in messages: row_values = [] for header in headers: # 处理None值,替换为空字符串 val = msg[header] if msg[header] is not None else "" row_values.append(str(val)) md_table += f"| {' | '.join(row_values)} |\n" # 输出或保存表格 print(md_table)
运行后输出的Markdown表格示例:
| Smstat | Index | Phone | Content | Date | Sca | SaveType | Priority | SmsType |
|---|---|---|---|---|---|---|---|---|
| 0 | 40006 | Ufone | SMS failed. | 2023-03-11 01:21:12 | 4 | 0 | 1 | |
| 0 | 40005 | Ufone | SMS failed. | 2023-03-11 01:21:06 | 4 | 0 | 1 |
方案2:控制台打印美观表格(适合调试查看)
借助prettytable库快速生成对齐整齐的控制台表格,方便调试时查看数据。
第一步:安装依赖库
pip install prettytable
第二步:代码实现
from huawei_lte_api.Client import Client from huawei_lte_api.Connection import Connection from prettytable import PrettyTable with Connection('http://admin:admin@192.168.8.1/') as connection: client = Client(connection) sms_list = client.sms.get_sms_list() messages = sms_list['Messages']['Message'] if not messages: print("无短信数据") exit() # 初始化表格并设置表头 table = PrettyTable() table.field_names = list(messages[0].keys()) # 添加每条短信数据 for msg in messages: row_data = [str(msg[field] if msg[field] is not None else "") for field in table.field_names] table.add_row(row_data) # 打印表格 print(table)
运行后控制台会输出对齐整齐的表格,示例:
+--------+--------+-------+-----------------+---------------------+------+----------+----------+---------+ | Smstat | Index | Phone | Content | Date | Sca | SaveType | Priority | SmsType | +--------+--------+-------+-----------------+---------------------+------+----------+----------+---------+ | 0 | 40006 | Ufone | SMS failed. | 2023-03-11 01:21:12 | | 4 | 0 | 1 | | 0 | 40005 | Ufone | SMS failed. | 2023-03-11 01:21:06 | | 4 | 0 | 1 | +--------+--------+-------+-----------------+---------------------+------+----------+----------+---------+
内容的提问来源于stack exchange,提问作者mshariq84
相关产品推荐
相关产品推荐

