本文目录导读:

我来帮你创建一个批量导出聊天记录为文档的脚本,这里提供几种常见聊天工具的导出脚本:
微信聊天记录导出脚本
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
微信聊天记录批量导出工具
支持导出为TXT、Word、PDF格式
"""
import os
import json
import sqlite3
import datetime
from pathlib import Path
import tempfile
import shutil
try:
from docx import Document
from docx.shared import Pt, Inches, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
DOCX_AVAILABLE = True
except ImportError:
DOCX_AVAILABLE = False
print("警告: 未安装python-docx,Word导出功能不可用")
try:
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter, A4
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
PDF_AVAILABLE = True
except ImportError:
PDF_AVAILABLE = False
print("警告: 未安装reportlab,PDF导出功能不可用")
class WeChatChatExporter:
"""微信聊天记录导出器"""
def __init__(self, db_path=None):
"""
初始化导出器
Args:
db_path: 微信数据库文件路径(可选,默认自动查找)
"""
self.db_path = db_path or self._find_wechat_db()
self.contacts_cache = {}
def _find_wechat_db(self):
"""自动查找微信数据库文件"""
# 常见微信数据库位置
possible_paths = [
# Windows
os.path.expanduser("~/Documents/WeChat Files"),
os.path.expanduser("~/WeChat Files"),
# Mac
os.path.expanduser("~/Library/Containers/com.tencent.xinWeChat/Data"),
os.path.expanduser("~/Library/Application Support/com.tencent.xinWeChat"),
]
for base_path in possible_paths:
if os.path.exists(base_path):
# 查找最新的聊天数据库
for root, dirs, files in os.walk(base_path):
for file in files:
if file in ['MSG.db', 'msg.db', 'message.db']:
return os.path.join(root, file)
raise FileNotFoundError("未找到微信数据库文件,请手动指定路径")
def get_chat_contacts(self):
"""获取所有聊天联系人"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# 获取联系人列表(根据实际数据库结构调整)
cursor.execute("""
SELECT
strUsrName,
strNickName,
strRemark,
iMaxMsgId
FROM Contact
ORDER BY strNickName
""")
contacts = cursor.fetchall()
conn.close()
return contacts
def export_single_chat(self, contact_name, output_format='txt', output_dir='exports'):
"""
导出单个联系人聊天记录
Args:
contact_name: 联系人名称
output_format: 导出格式 (txt/docx/pdf)
output_dir: 导出目录
"""
# 创建导出目录
Path(output_dir).mkdir(parents=True, exist_ok=True)
# 查询聊天记录
messages = self._fetch_messages(contact_name)
if not messages:
print(f"未找到与 {contact_name} 的聊天记录")
return None
# 根据格式导出
output_file = Path(output_dir) / f"chat_{contact_name}_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.{output_format}"
if output_format == 'txt':
self._export_txt(messages, output_file)
elif output_format == 'docx' and DOCX_AVAILABLE:
self._export_docx(messages, output_file)
elif output_format == 'pdf' and PDF_AVAILABLE:
self._export_pdf(messages, output_file)
else:
raise ValueError(f"不支持的导出格式: {output_format}")
print(f"已导出 {contact_name} 的聊天记录到 {output_file}")
return output_file
def export_all_chats(self, output_format='txt', output_dir='exports'):
"""导出所有聊天记录"""
print("获取联系人列表...")
contacts = self.get_chat_contacts()
if not contacts:
print("未找到任何聊天记录")
return []
exported_files = []
total = len(contacts)
print(f"找到 {total} 个聊天会话,开始导出...")
for i, contact in enumerate(contacts, 1):
contact_name = contact[2] or contact[1] or contact[0]
print(f"[{i}/{total}] 导出 {contact_name}...")
try:
file = self.export_single_chat(contact_name, output_format, output_dir)
if file:
exported_files.append(file)
except Exception as e:
print(f"导出 {contact_name} 失败: {e}")
continue
print(f"\n导出完成!共导出 {len(exported_files)} 个聊天记录")
return exported_files
def _fetch_messages(self, contact_name):
"""从数据库获取聊天记录"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# 查询聊天记录(根据实际数据库结构调整)
cursor.execute("""
SELECT
CreateTime,
strContent,
type,
isSend
FROM Message
WHERE strTalker = ?
ORDER BY CreateTime ASC
""", (contact_name,))
messages = cursor.fetchall()
conn.close()
# 格式化时间戳
formatted_messages = []
for msg in messages:
try:
timestamp = msg[0]
if timestamp > 10000000000: # 毫秒转秒
timestamp = timestamp / 1000
msg_time = datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
except:
msg_time = str(msg[0])
formatted_messages.append({
'time': msg_time,
'content': msg[1],
'type': msg[2],
'is_send': msg[3] == 1 # 1表示发送,0表示接收
})
return formatted_messages
def _export_txt(self, messages, output_file):
"""导出为TXT格式"""
with open(output_file, 'w', encoding='utf-8') as f:
for msg in messages:
sender = "我" if msg['is_send'] else "对方"
f.write(f"[{msg['time']}] {sender}: {msg['content']}\n\n")
def _export_docx(self, messages, output_file):
"""导出为Word格式"""
doc = Document()
# 设置标题样式
title_style = doc.styles['Title']
title_style.font.size = Pt(18)
title_style.font.color.rgb = RGBColor(0x2F, 0x54, 0x96)
doc.add_heading('聊天记录导出', 0)
doc.add_paragraph(f'导出时间: {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
for msg in messages:
sender = "我" if msg['is_send'] else "对方"
# 创建段落
paragraph = doc.add_paragraph()
# 时间样式
time_run = paragraph.add_run(f"[{msg['time']}] ")
time_run.font.color.rgb = RGBColor(0x66, 0x66, 0x66)
time_run.font.size = Pt(10)
# 发送者样式
sender_run = paragraph.add_run(f"{sender}: ")
if msg['is_send']:
sender_run.font.color.rgb = RGBColor(0x00, 0x66, 0xCC)
else:
sender_run.font.color.rgb = RGBColor(0xCC, 0x44, 0x44)
sender_run.bold = True
# 消息内容
content_run = paragraph.add_run(str(msg['content']))
content_run.font.size = Pt(11)
# 添加间距
paragraph.paragraph_format.space_after = Pt(12)
doc.save(str(output_file))
def _export_pdf(self, messages, output_file):
"""导出为PDF格式"""
doc = SimpleDocTemplate(
str(output_file),
pagesize=A4,
rightMargin=72,
leftMargin=72,
topMargin=72,
bottomMargin=72
)
styles = getSampleStyleSheet()
# 自定义样式
title_style = ParagraphStyle(
'CustomTitle',
parent=styles['Title'],
fontSize=24,
spaceAfter=30
)
time_style = ParagraphStyle(
'TimeStyle',
fontName='Helvetica',
fontSize=9,
textColor=colors.grey,
alignment=1 # 居中
)
message_styles = {
'sent': ParagraphStyle(
'SentMessage',
parent=styles['Normal'],
fontSize=11,
textColor=colors.blue,
leftIndent=20,
spaceAfter=6
),
'received': ParagraphStyle(
'ReceivedMessage',
parent=styles['Normal'],
fontSize=11,
textColor=colors.black,
rightIndent=20,
spaceAfter=6
)
}
# 添加标题
elements = []
elements.append(Paragraph("聊天记录导出", title_style))
elements.append(Paragraph(
f'导出时间: {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}',
time_style
))
elements.append(Spacer(1, 20))
# 添加消息
for msg in messages:
sender = "我" if msg['is_send'] else "对方"
# 使用HTML格式创建段落
color = "#0066CC" if msg['is_send'] else "#CC4444"
html_content = f'<span color="{color}"><b>{sender}</b></span> [{msg["time"}]<br/>{msg["content"]}'
style = message_styles['sent'] if msg['is_send'] else message_styles['received']
elements.append(Paragraph(html_content, style))
elements.append(Spacer(1, 2))
doc.build(elements)
class ChatExporterFactory:
"""聊天导出器工厂"""
@staticmethod
def create_exporter(chat_type='wechat', *args, **kwargs):
"""
创建对应的聊天导出器
Args:
chat_type: 聊天工具类型 ('wechat', 'qq', 'telegram', 'whatsapp' 等)
*args: 传递给导出器的位置参数
**kwargs: 传递给导出器的关键字参数
"""
exporters = {
'wechat': WeChatChatExporter,
# 在这里可以添加更多聊天工具的支持
# 'qq': QQChatExporter,
# 'telegram': TelegramChatExporter,
# 'whatsapp': WhatsAppChatExporter,
}
if chat_type not in exporters:
raise ValueError(f"不支持的聊天类型: {chat_type},可用的类型: {list(exporters.keys())}")
return exporters[chat_type](*args, **kwargs)
def batch_export_chats(chat_type='wechat', db_path=None, output_format='txt', output_dir='exports', selected_contacts=None):
"""
批量导出聊天记录的主函数
Args:
chat_type: 聊天工具类型
db_path: 数据库路径(微信专用)
output_format: 导出格式 ('txt', 'docx', 'pdf')
output_dir: 导出目录
selected_contacts: 选择导出的联系人列表(None表示全部)
Returns:
list: 导出的文件路径列表
"""
try:
# 创建导出器
exporter = ChatExporterFactory.create_exporter(chat_type, db_path)
# 获取联系人列表
contacts = exporter.get_chat_contacts()
if selected_contacts:
# 只导出选定的联系人
contacts = [c for c in contacts if c[2] or c[1] in selected_contacts]
if not contacts:
print("未找到聊天记录")
return []
exported_files = []
total = len(contacts)
print(f"准备导出 {total} 个聊天会话")
# 创建进度条
for i, contact in enumerate(contacts, 1):
contact_name = contact[2] or contact[1] or contact[0]
print(f"正在导出 [{i}/{total}] {contact_name}...")
try:
file = exporter.export_single_chat(
contact_name,
output_format,
output_dir
)
if file:
exported_files.append(file)
print(f" ✓ 成功: {file.name}")
except Exception as e:
print(f" ✗ 失败: {e}")
continue
# 生成汇总报告
summary_file = Path(output_dir) / "export_summary.txt"
with open(summary_file, 'w', encoding='utf-8') as f:
f.write(f"聊天记录导出汇总\n")
f.write(f"导出时间: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write(f"导出格式: {output_format}\n")
f.write(f"成功导出: {len(exported_files)}/{total}\n\n")
f.write("导出文件列表:\n")
for file in exported_files:
f.write(f" - {file}\n")
print(f"\n导出完成!")
print(f"成功导出: {len(exported_files)}/{total} 个聊天记录")
print(f"文件保存在: {output_dir}")
print(f"汇总报告: {summary_file}")
return exported_files
except Exception as e:
print(f"批量导出失败: {e}")
return []
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="批量导出聊天记录")
parser.add_argument('--type', default='wechat', help='聊天类型 (wechat, qq, telegram等)')
parser.add_argument('--db', help='数据库文件路径')
parser.add_argument('--format', default='txt', choices=['txt', 'docx', 'pdf'], help='导出格式')
parser.add_argument('--output', default='exports', help='导出目录')
parser.add_argument('--contacts', nargs='*', help='选择联系人(留空导出全部)')
args = parser.parse_args()
print("=" * 50)
print("聊天记录批量导出工具")
print("=" * 50)
batch_export_chats(
chat_type=args.type,
db_path=args.db,
output_format=args.format,
output_dir=args.output,
selected_contacts=args.contacts
)
简易版本(适用于通用的文本聊天记录)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简易聊天记录导出工具
适用于常见的文本格式聊天记录
"""
import os
import re
from pathlib import Path
import datetime
import argparse
class SimpleChatExporter:
"""简易聊天记录导出器"""
def __init__(self, input_format='txt'):
self.input_format = input_format
self.supported_formats = ['txt', 'csv', 'json']
def export_from_txt(self, input_file, output_format='txt', output_dir='exports'):
"""
从TXT文件导出聊天记录
Args:
input_file: 聊天记录文件路径
output_format: 导出格式
output_dir: 导出目录
"""
# 读取文件
with open(input_file, 'r', encoding='utf-8') as f:
content = f.read()
# 解析聊天记录
messages = self._parse_txt_chat(content)
# 创建输出目录
Path(output_dir).mkdir(parents=True, exist_ok=True)
# 生成输出文件
timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
output_file = Path(output_dir) / f"chat_export_{timestamp}.{output_format}"
if output_format == 'txt':
self._write_txt(messages, output_file)
elif output_format == 'csv':
self._write_csv(messages, output_file)
elif output_format == 'json':
self._write_json(messages, output_file)
else:
raise ValueError(f"不支持的输出格式: {output_format}")
print(f"已导出 {len(messages)} 条聊天记录到 {output_file}")
return output_file
def _parse_txt_chat(self, content):
"""
解析TXT聊天记录格式,支持多种常见格式:
1. [2024-01-01 12:00:00] 张三: 你好
2. 2024-01-01 12:00:00 张三: 你好
3. 张三 2024-01-01 12:00:00: 你好
"""
messages = []
# 支持多种时间格式
patterns = [
# [时间] 发送者: 消息
r'\[(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})\]\s*([^:]+):\s*(.+)',
# 时间 发送者: 消息
r'(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})\s+([^:]+):\s*(.+)',
# 发送者 时间: 消息
r'([^:]+)\s+(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}):\s*(.+)',
]
for line in content.split('\n'):
line = line.strip()
if not line:
continue
matched = False
for pattern in patterns:
match = re.match(pattern, line)
if match:
if len(match.groups()) == 3:
time_str, sender, message = match.groups()
messages.append({
'time': time_str,
'sender': sender.strip(),
'content': message.strip()
})
matched = True
break
if not matched:
# 非标准格式,作为普通消息处理
messages.append({
'time': '',
'sender': '',
'content': line
})
return messages
def _write_txt(self, messages, output_file):
"""写入TXT文件"""
with open(output_file, 'w', encoding='utf-8') as f:
f.write("聊天记录导出\n")
f.write(f"导出时间: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write("=" * 50 + "\n\n")
for msg in messages:
if msg['time'] and msg['sender']:
f.write(f"[{msg['time']}] {msg['sender']}: {msg['content']}\n")
else:
f.write(f"{msg['content']}\n")
f.write("\n")
def _write_csv(self, messages, output_file):
"""写入CSV文件"""
import csv
with open(output_file, 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
writer.writerow(['时间', '发送者', '内容'])
for msg in messages:
writer.writerow([msg['time'], msg['sender'], msg['content']])
def _write_json(self, messages, output_file):
"""写入JSON文件"""
import json
data = {
'export_time': datetime.datetime.now().isoformat(),
'message_count': len(messages),
'messages': messages
}
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
def main():
"""主函数"""
parser = argparse.ArgumentParser(description='聊天记录导出工具')
parser.add_argument('--input', required=True, help='输入聊天记录文件')
parser.add_argument('--format', default='txt', choices=['txt', 'csv', 'json'], help='导出格式')
parser.add_argument('--output', default='exports', help='输出目录')
parser.add_argument('--contacts', nargs='*', help='选择联系人(可选)')
args = parser.parse_args()
# 检查输入文件
if not os.path.exists(args.input):
print(f"错误: 输入文件不存在 - {args.input}")
return 1
try:
exporter = SimpleChatExporter()
result = exporter.export_from_txt(
args.input,
output_format=args.format,
output_dir=args.output
)
print(f"导出成功: {result}")
return 0
except Exception as e:
print(f"导出失败: {e}")
return 1
if __name__ == "__main__":
exit(main())
使用说明
安装依赖
对于完整版(微信导出):
# 使用pip安装所需库 pip install python-docx reportlab
对于简易版(文本格式导出):
# 无需额外依赖,Python 3.6+ 即可运行
基本用法
# 1. 简易版本 - 导出文本聊天记录 python chat_exporter.py --input 聊天记录.txt --format txt --output exports/ # 2. 简易版本 - 导出为CSV格式 python chat_exporter.py --input 聊天记录.txt --format csv # 3. 简易版本 - 导出为JSON格式 python chat_exporter.py --input 聊天记录.txt --format json # 4. 完整版本 - 导出微信聊天记录 python wechat_exporter.py --type wechat --format docx --output exports/ # 5. 完整版本 - 导出微信聊天记录为PDF python wechat_exporter.py --type wechat --format pdf --output pdf_exports/ # 6. 导出特定联系人 python wechat_exporter.py --type wechat --format txt --contacts "张三" "李四"
功能特性
- 多种格式支持: TXT、Word、PDF、CSV、JSON
- 批量处理: 自动导出所有聊天记录
- 联系人选择: 可选择导出特定联系人
- 进度显示: 实时显示导出进度
- 错误处理: 单个联系人导出失败不影响其他记录
- 汇总报告: 生成导出汇总文件
注意事项
- 微信数据库访问: 可能需要管理员权限访问微信数据库
- 隐私保护: 导出文件包含个人隐私信息,请妥善保存
- 大文件处理: 处理大量聊天记录时可能需要较长时间
- 格式兼容性: 不同版本的微信数据库结构可能不同
这个脚本提供了完整的功能,你可以根据需要选择合适的版本使用,如果需要调整或扩展功能,请告诉我!