如何将Python情绪追踪器的输出写入Google文档?
可行解决方案
一、先解决数据持久化问题
你现有代码里的journal列表是存在内存里的,程序一关闭数据就没了,所以第一步得把数据写到本地存储里,比如文件或数据库,这样下次运行程序还能读取之前的数据。
1. 用JSON文件存储(轻量易上手)
JSON格式适合存结构化数据,修改你的类,加上读写JSON文件的逻辑:
import datetime import json import os class Documentation: def __init__(self): self.journal_file = "emotion_journal.json" # 初始化时加载已存的数据 self.journal = self._load_from_file() def _load_from_file(self): # 文件存在就读取,否则返回空列表 if os.path.exists(self.journal_file): with open(self.journal_file, "r", encoding="utf-8") as f: return json.load(f) return [] def get_current_datetime(self): now = datetime.datetime.now() return now.strftime("%Y/%m/%d"), now.strftime("%H:%M:%S") def add_emotion_entry(self, emotion_data): # 获取当前日期时间 date, time = self.get_current_datetime() # 构造条目 entry = {"date": date, "time": time, "emotions": emotion_data} self.journal.append(entry) # 写入文件保存 self._save_to_file() print("情绪记录已保存") def _save_to_file(self): with open(self.journal_file, "w", encoding="utf-8") as f: json.dump(self.journal, f, indent=2, ensure_ascii=False) def show_all_entries(self): for entry in self.journal: emotion_str = ", ".join([f"'{k}': {v}" for k, v in entry['emotions'].items()]) print(f"{entry['date']} {entry['time']} - {emotion_str}")
使用示例:
# 实例化类 doc = Documentation() # 假设你的情绪追踪器生成的结果 emotion_result = {'Happy': 0.67, 'Angry': 0.0, 'Surprise': 0.33} # 添加记录 doc.add_emotion_entry(emotion_result) # 查看所有记录 doc.show_all_entries()
2. 用SQLite数据库(适合大量数据)
如果后续数据量变大,用SQLite更高效,不需要额外装数据库服务:
import datetime import sqlite3 class Documentation: def __init__(self): # 连接数据库(文件不存在会自动创建) self.conn = sqlite3.connect("emotion_tracker.db") self.cursor = self.conn.cursor() # 创建情绪记录表 self._create_table() def _create_table(self): self.cursor.execute(''' CREATE TABLE IF NOT EXISTS emotion_entries ( id INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT NOT NULL, time TEXT NOT NULL, happy REAL, angry REAL, surprise REAL ) ''') self.conn.commit() def get_current_datetime(self): now = datetime.datetime.now() return now.strftime("%Y/%m/%d"), now.strftime("%H:%M:%S") def add_emotion_entry(self, happy, angry, surprise): date, time = self.get_current_datetime() self.cursor.execute(''' INSERT INTO emotion_entries (date, time, happy, angry, surprise) VALUES (?, ?, ?, ?, ?) ''', (date, time, happy, angry, surprise)) self.conn.commit() print("情绪记录已保存") def show_all_entries(self): self.cursor.execute('SELECT date, time, happy, angry, surprise FROM emotion_entries') for row in self.cursor.fetchall(): print(f"{row[0]} {row[1]} - 'Happy': {row[2]}, 'Angry': {row[3]}, 'Surprise': {row[4]}") def __del__(self): # 实例销毁时关闭数据库连接 self.conn.close()
使用示例:
doc = Documentation() # 传入情绪追踪器生成的数值 doc.add_emotion_entry(happy=0.67, angry=0.0, surprise=0.33) doc.show_all_entries()
二、同步到Google文档
要把数据写到Google文档,得用Google Workspace API,步骤如下:
1. 前期准备
- 去Google Cloud控制台创建项目,启用Google Docs API和Google Drive API
- 创建服务账号,下载JSON格式的密钥文件
- 新建一个Google文档,把服务账号的邮箱添加为该文档的编辑者
2. 代码实现同步
先安装依赖:
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib
编写同步类:
from googleapiclient.discovery import build from google.oauth2 import service_account class GoogleDocsSync: def __init__(self, doc_id, credentials_path): self.doc_id = doc_id # 加载服务账号密钥 self.credentials = service_account.Credentials.from_service_account_file( credentials_path, scopes=["https://www.googleapis.com/auth/documents", "https://www.googleapis.com/auth/drive"] ) self.service = build('docs', 'v1', credentials=self.credentials) def append_to_doc(self, entry_str): # 获取文档末尾位置 doc = self.service.documents().get(documentId=self.doc_id).execute() end_index = doc['body']['content'][-1]['endIndex'] - 1 # 构造插入请求 requests = [ { 'insertText': { 'location': {'index': end_index}, 'text': f"{entry_str}\n\n" } } ] # 执行插入 self.service.documents().batchUpdate( documentId=self.doc_id, body={'requests': requests} ).execute()
结合之前的JSON存储类使用:
# 替换成你的文档ID和密钥文件路径 docs_sync = GoogleDocsSync("你的Google文档ID", "service_account_key.json") doc = Documentation() emotion_result = {'Happy': 0.67, 'Angry': 0.0, 'Surprise': 0.33} doc.add_emotion_entry(emotion_result) # 构造要写入文档的字符串 date, time = doc.get_current_datetime() entry_str = f"{date} - {', '.join([f'{k}: {v}' for k, v in emotion_result.items()])}" # 同步到Google文档 docs_sync.append_to_doc(entry_str)
三、你原有代码的问题说明
global journal放在类里会导致每次实例化类时重置列表,而且全局变量管理混乱time方法和实例属性self.time重名,运行会报错allDocument方法不需要传date, time, notes参数,直接遍历journal即可- 没有持久化逻辑,程序结束数据就丢失
上面的方案已经重构了这些问题,实现了数据持久化和Google文档同步。
内容的提问来源于stack exchange,提问作者Alvino123
相关产品推荐
相关产品推荐

