ZuAnBot icon indicating copy to clipboard operation
ZuAnBot copied to clipboard

建议支持批量导入词库,限制发送频率功能

Open Cormac315 opened this issue 1 year ago • 0 comments

希望在UI页面加入批量导入词库,限制发送频率功能 另外提供一种手动批量导入词库方式(3.0.1版本) 默认的词库目录在C:\Users\用户名称\AppData\Local\ZuAnBot 可使用下面脚本将txt文件中的词条(一行一条)批量导入到json

import json

# 文件路径
json_file_path = "wordsLibrary.json"
custom_txt_path = "Custom.txt"

def load_json(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"文件 {file_path} 未找到。")
        return None
    except json.JSONDecodeError:
        print(f"文件 {file_path} 不是有效的 JSON 格式。")
        return None

def save_json(file_path, data):
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=4)
        print(f"成功保存到 {file_path}")
    except Exception as e:
        print(f"保存文件时出错: {e}")

def load_custom_words(file_path, max_length=200):
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return [line.strip() for line in f if line.strip() and len(line.strip()) <= max_length]
    except FileNotFoundError:
        print(f"文件 {file_path} 未找到。")
        return None

def add_custom_words_to_json(json_data, custom_words):
    if not json_data or not custom_words:
        return

    for category in json_data["Categories"]:
        if category["CategoryName"] == "自定义词库":
            existing_words = {word["Content"] for word in category["Words"]}
            for word in custom_words:
                if word not in existing_words:
                    category["Words"].append({"Content": word})
            break
    else:
        json_data["Categories"].append({
            "Words": [{"Content": word} for word in custom_words],
            "CategoryName": "自定义词库",
            "CopyToCommand": {
                "IsActive": False
            }
        })

def main():
    json_data = load_json(json_file_path)
    if json_data is None:
        return

    # 舍弃长度超过30字符的词条
    custom_words = load_custom_words(custom_txt_path, max_length=30)
    if custom_words is None:
        return

    add_custom_words_to_json(json_data, custom_words)
    save_json(json_file_path, json_data)

if __name__ == "__main__":
    main()

Cormac315 avatar Oct 05 '24 07:10 Cormac315