You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python解析短信文本文件并转换为结构化CSV格式?

短信文本提取并生成结构化表格的解决方案

问题场景

我有一个纯文本格式的短信文件,格式如下:

Sent on 1/1/2023 7:30:33 AM to Person1

Message

-----

Received on 5/20/2023 4:55:33 PM from Person1

Message

需要遍历该文本文件,提取相关内容并生成如下结构化表格:

StatusDateContactMessage
Sent1/1/2023 7:30:33 AMPerson1Message
Received5/20/2023 4:55:33 PMPerson1Message

原代码仅简单按行读取文本写入Excel,无法实现内容解析与结构化:

import csv
import openpyxl

input_file = 'output.txt'
output_file = 'allmessages.csv'

wb = openpyxl.Workbook()
ws = wb.worksheets[0]

with open(input_file, 'r') as data:
    reader = csv.reader(data, delimiter='\t')
    for row in reader:
        ws.append(row)
        
wb.save(output_file)

解决思路与实现代码

核心是先按分隔符拆分短信块,再逐个解析每个块里的关键信息,最后写入结构化文件。

方法一:生成Excel文件

import openpyxl

input_file = 'output.txt'
output_file = 'allmessages.xlsx'

# 读取完整文本内容
with open(input_file, 'r', encoding='utf-8') as f:
    content = f.read()

# 拆分短信块并过滤空内容
sms_blocks = [block.strip() for block in content.split('-----') if block.strip()]

# 初始化Excel工作簿
wb = openpyxl.Workbook()
ws = wb.active
# 写入表头
ws.append(['Status', 'Date', 'Contact', 'Message'])

for block in sms_blocks:
    # 清理块内空行,保留有效内容
    lines = [line.strip() for line in block.split('\n') if line.strip()]
    if len(lines) < 2:
        continue  # 跳过无效短信块
    
    # 解析状态、日期、联系人
    first_line = lines[0]
    if first_line.startswith('Sent'):
        status = 'Sent'
        # 拆分格式:"Sent on [日期] to [联系人]"
        date_part, contact_part = first_line.split(' on ', 1)[1].split(' to ', 1)
        date_str = date_part.strip()
        contact = contact_part.strip()
    elif first_line.startswith('Received'):
        status = 'Received'
        # 拆分格式:"Received on [日期] from [联系人]"
        date_part, contact_part = first_line.split(' on ', 1)[1].split(' from ', 1)
        date_str = date_part.strip()
        contact = contact_part.strip()
    else:
        continue  # 跳过无法识别的短信
    
    # 提取完整消息内容
    message = '\n'.join(lines[1:]).strip()
    
    # 写入Excel行
    ws.append([status, date_str, contact, message])

# 保存文件
wb.save(output_file)
print(f"文件 {output_file} 已生成")

方法二:生成CSV文件

如果需要CSV格式,可使用csv模块实现:

import csv

input_file = 'output.txt'
output_file = 'allmessages.csv'

with open(input_file, 'r', encoding='utf-8') as f:
    content = f.read()

sms_blocks = [block.strip() for block in content.split('-----') if block.strip()]

with open(output_file, 'w', newline='', encoding='utf-8') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['Status', 'Date', 'Contact', 'Message'])
    
    for block in sms_blocks:
        lines = [line.strip() for line in block.split('\n') if line.strip()]
        if len(lines) < 2:
            continue
        
        first_line = lines[0]
        if first_line.startswith('Sent'):
            status = 'Sent'
            date_part, contact_part = first_line.split(' on ', 1)[1].split(' to ', 1)
            date_str = date_part.strip()
            contact = contact_part.strip()
        elif first_line.startswith('Received'):
            status = 'Received'
            date_part, contact_part = first_line.split(' on ', 1)[1].split(' from ', 1)
            date_str = date_part.strip()
            contact = contact_part.strip()
        else:
            continue
        
        message = '\n'.join(lines[1:]).strip()
        writer.writerow([status, date_str, contact, message])

print(f"文件 {output_file} 已生成")

关键逻辑说明

  • 拆分短信块:用-----作为分隔符,将整个文本拆分为独立的短信单元,同时过滤掉空的无效块
  • 解析内容:通过判断第一行的Sent/Received标识状态,再用字符串拆分提取日期和联系人;消息内容为块内除第一行外的所有有效内容拼接
  • 结构化写入:先写入表头,再将每条短信的结构化数据逐行写入文件

内容的提问来源于stack exchange,提问作者user21407177

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 11:34:56