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

如何开发支持持久化记忆的独立问答应用(Python/Windows&Android)

Windows 版本实现(Python)

核心逻辑代码

用JSON文件做持久化存储,替代内存字典,确保程序关闭后数据保留。以下是完整可运行的脚本:

import json
import os

# 数据存储路径,放在用户文档目录,避免权限问题
DATA_FILE = os.path.join(os.path.expanduser("~"), "facts_storage.json")

def load_data():
    """加载存储的事实数据"""
    if os.path.exists(DATA_FILE):
        with open(DATA_FILE, 'r', encoding='utf-8') as f:
            try:
                return json.load(f)
            except json.JSONDecodeError:
                return {}
    return {}

def save_data(data):
    """保存事实数据到文件"""
    with open(DATA_FILE, 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=2, ensure_ascii=False)

def input_fact():
    """录入事实功能"""
    print("\n请按格式录入事实(例如:bird = flying animal with feathers)")
    input_line = input("> ").strip()
    if '=' not in input_line:
        print("格式错误,请包含 '=' 分隔主题和内容")
        return
    # 按第一个=分割主题和内容
    key, value = input_line.split('=', 1)
    key = key.strip().lower()  # 统一小写,避免大小写重复存储
    value = value.strip()
    data = load_data()
    data[key] = value
    save_data(data)
    print(f"已保存事实:{key} = {value}")

def recall_fact():
    """召回事实功能"""
    print("\n请输入查询指令(例如:Recall bird 或 Recall ALL DATA)")
    input_line = input("> ").strip().lower()
    if not input_line.startswith("recall "):
        print("指令错误,请以 'Recall ' 开头")
        return
    query = input_line[7:].strip()
    data = load_data()
    if query == "all data":
        if not data:
            print("暂无存储数据")
            return
        print("\n全部存储数据:")
        for key, value in data.items():
            print(f"{key} = {value}")
    else:
        if query in data:
            print(f"{query.capitalize()} is {data[query]}")
        else:
            print(f"未找到关于 '{query}' 的事实")

def main():
    """主程序入口"""
    while True:
        print("\n=== 自定义事实存储工具 ===")
        print("1. Input(录入事实)")
        print("2. Recall(查询事实)")
        print("3. Exit(退出)")
        choice = input("请选择操作(1/2/3):").strip()
        if choice == '1':
            input_fact()
        elif choice == '2':
            recall_fact()
        elif choice == '3':
            print("程序已退出")
            break
        else:
            print("无效选择,请重新输入")

if __name__ == "__main__":
    main()

打包成独立Windows应用

  1. 安装打包工具:pip install pyinstaller
  2. 执行打包命令:pyinstaller --onefile --name FactStorage main.py
    • --onefile:生成单个可执行文件
    • 若需要隐藏控制台窗口,添加--windowed参数(注意:此参数会屏蔽所有print输出,如需保留交互需改用图形界面)
  3. 打包后的可执行文件在dist目录下,直接运行即可,数据会自动存在用户文档目录的facts_storage.json中。

Android版本实现方案

方案1:Python跨平台(Kivy)

适合熟悉Python的开发者,可复用核心存储逻辑:

  1. 安装Kivy框架:pip install kivy
  2. 编写Kivy图形界面代码,替换命令行交互;核心的load_data和save_data逻辑可复用,存储路径改为Android应用的私有目录(通过kivy.utils.platform获取)
  3. 用Buildozer打包APK:
    • 安装Buildozer:pip install buildozer
    • 初始化配置文件:buildozer init,修改配置中的package.name、package.domain等参数
    • 执行打包:buildozer android debug

方案2:原生Android开发(Kotlin/Java)

适合追求原生体验和性能的场景:

  1. 存储方案:用SharedPreferences(适合键值对存储)或SQLite(后续扩展复杂数据时使用)
  2. 界面实现:
    • 主界面设置三个操作按钮:Input、Recall、Exit
    • Input页面:用输入框接收格式文本,分割后将键值对保存到存储
    • Recall页面:用输入框接收查询指令,处理"Recall ALL DATA"和单个主题查询,返回对应内容
  3. 核心逻辑:
    • 存储:通过SharedPreferences.Editor写入键值对,自动覆盖旧值
    • 查询:解析指令后读取对应键的值,或遍历所有键值对返回全部数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 22:53:11