测试data_management函数

测试data_management函数

这是我最近正在开发的AI工具信息平台的部门功能模块测试,基于streamlit架构。整理出来与大家分享,也为我以后自己回溯找到资源。

为了测试 data_management 函数并结合 Excel 文件中的 “Tools” 表单内容,我们需要进行以下步骤:

  1. 确保 Excel 文件准备好:你的 Excel 文件(例如 test_tools.xlsx)应包含相关的工具数据。
  2. 实现 save_all_data 函数:确保有一个函数用于保存数据回 Excel 文件。
  3. 编写完整的测试代码:将 data_management 函数整合到一个 Streamlit 应用中,以便从 Excel 读取数据、执行管理操作并实时展示结果。

步骤 1:准备 Excel 文件

确保你的 Excel 文件 test_tools.xlsx 内容如下:

NameCategoryCountryCompanyDescriptionURLOpen SourcePopularityLastUpdated
通义千问大语言模型中国阿里巴巴阿里云企业级大模型平台https://tongyi.aliyun.com4002024/2/11
智谱清言App大语言模型中国智谱AI新一代认知智能大模型,提供对话、问答等功能https://chatglm.cn/50002025/1/22
Tool A大语言模型USACompany AA great toolhttp://example.com1002023/1/1
Tool B大语言模型CanadaCompany BAnother great toolhttp://example2.com2002023/1/2
Tool C大语言模型UKCompany CAmazing toolhttp://example3.com1502023/1/3

步骤 2:实现 save_all_data 函数

确保你能将数据保存回 Excel 文件。以下是一个简单的示例实现:

def save_all_data(excel_file, tools_data, tutorials_data):
    """保存所有数据到 Excel 文件"""
    with pd.ExcelWriter(excel_file) as writer:
        # 将工具数据写入工作表
        for category, items in tools_data.items():
            df = pd.DataFrame(items)
            df.to_excel(writer, sheet_name=category, index=False)
        
        # 如果有教程数据,也可以保存到对应的工作表
        if tutorials_data:  # 示例,如果有必要可以添加处理
            tutorials_df = pd.DataFrame(tutorials_data)
            tutorials_df.to_excel(writer, sheet_name='Tutorials', index=False)

    return True

步骤 3:编写完整的 Streamlit 应用代码

data_management 函数整合到一个完整的 Streamlit 应用中,读取 Excel 文件并实现数据的管理功能:

import pandas as pd
import streamlit as st
import datetime

# 国家标志示例
COUNTRY_FLAGS = {
    '中国': '🇨🇳',
    'USA': '🇺🇸',
    'Canada': '🇨🇦',
    'UK': '🇬🇧'
}

def save_all_data(excel_file, tools_data, tutorials_data):
    """保存所有数据到Excel"""
    try:
        tools_rows = []
        for category, items in tools_data.items():
            for item in items:
                tools_rows.append({
                    'Name': item['name'],
                    'Category': category,
                    'Country': item['country'],
                    'Company': item.get('company', ''),
                    'Description': item['description'],
                    'URL': item['url'],
                    'Open Source': item['open_source']
                })
        tools_df = pd.DataFrame(tools_rows)

        tutorials_rows = []
        for tool_name, tutorials in tutorials_data.items():
            for tut in tutorials:
                tutorials_rows.append({
                    'TutorialID': tut['id'],
                    'RelatedTool': tool_name,
                    'Title': tut['title'],
                    'URL': tut['url'],
                    'Type': tut['type'],
                    'DifficultyLevel': tut['difficulty'],
                    'Duration': tut.get('duration', ''),
                    'Rating': tut.get('rating', None),
                    'Language': tut.get('language', '中文'),
                    'Tags': ', '.join(tut.get('tags', [])),
                    'VersionCompatible': tut.get('version', ''),
                    'Author': tut.get('author', '')
                })
        tutorials_df = pd.DataFrame(tutorials_rows)

        with pd.ExcelWriter(excel_file, engine='openpyxl') as writer:
            tools_df.to_excel(writer, sheet_name='Tools', index=False)
            tutorials_df.to_excel(writer, sheet_name='Tutorials', index=False)
        return True
    except Exception as e:
        st.error(f"保存失败:{str(e)}")
        return False

class EnhancedConfig:
    SERPER_API_KEY = 'your api_key'  # 替换为实际的 API 密钥


def render_url(url):
    """根据URL生成超链接"""
    if url and url != '无':
        return f'<a href="{url}" class="link-btn" target="_blank">{url}</a>'
    else:
        return "<span>无可用链接</span>"


def classify_tool(name, description):
    """模拟分类工具的功能"""
    return '大语言模型'  # 示例返回


def data_management(excel_file, tools_data):
    # 新增分类验证功能
    if st.sidebar.button("🔍 分类质量检查"):
        error_count = 0
        for category, items in tools_data.items():
            for item in items:
                predicted = classify_tool(item['name'], item['description'])
                if predicted != category:
                    st.warning(f"分类不一致:{item['name']} 当前分类:{category},预测分类:{predicted}")
                    error_count += 1
        st.info(f"完成检查,发现{error_count}个潜在分类问题")

    # 数据管理界面
    st.sidebar.subheader("数据管理")
    operation = st.sidebar.radio("操作类型", ["添加条目", "编辑条目", "删除分类", "增加分类"])

    if operation == "添加条目":
        category = st.selectbox("选择分类", list(tools_data.keys()) + ["新增分类"])
        if category == "新增分类":
            category = st.text_input("请输入新分类名称")

        with st.form("添加表单"):
            name = st.text_input("工具名称")
            url = st.text_input("官网URL")
            country = st.selectbox("所属国家", list(COUNTRY_FLAGS.keys()))
            company = st.text_input("公司名称")
            description = st.text_area("工具描述")
            open_source = st.selectbox("是否开源", ["是", "否"])
            popularity = st.slider("初始流行度", 500, 2000, 1000)

            if st.form_submit_button("提交"):
                if all([category, name, url]):
                    new_item = {
                        'name': name,
                        'url': url,
                        'description': description,
                        'country': country,
                        'open_source': open_source,
                        'company': company,
                        'popularity': popularity,
                        'last_updated': datetime.datetime.now()
                    }
                    if category not in tools_data:
                        tools_data[category] = []
                    tools_data[category].append(new_item)

                    if save_all_data(excel_file, tools_data, {}):  # 假设没有教程数据
                        st.success("添加成功!")
                else:
                    st.error("请填写必填字段(分类、名称、URL)")

    elif operation == "编辑条目":
        category = st.selectbox("选择分类", list(tools_data.keys()))
        items = tools_data.get(category, [])

        if items:
            index = st.selectbox("选择条目", range(len(items)), format_func=lambda x: items[x]['name'])

            with st.form("编辑表单"):
                new_category = st.text_input("新分类名称", value=category)
                name = st.text_input("工具名称", value=items[index]['name'])
                url = st.text_input("官网URL", value=items[index]['url'])

                # 确保安全地获取国家
                try:
                    selected_country_index = list(COUNTRY_FLAGS.keys()).index(items[index]['country'])
                except ValueError:
                    selected_country_index = 0  # 默认到第一个国家

                country = st.selectbox("所属国家", list(COUNTRY_FLAGS.keys()), index=selected_country_index)
                company = st.text_input("公司名称", value=items[index]['company'])
                description = st.text_area("工具描述", value=items[index]['description'])
                open_source = st.selectbox("是否开源", ["是", "否"],
                                           index=["是", "否"].index(items[index]['open_source']))

                if st.form_submit_button("保存修改"):
                    del tools_data[category][index]
                    if new_category not in tools_data:
                        tools_data[new_category] = []
                    tools_data[new_category].append({
                        'name': name,
                        'url': url,
                        'description': description,
                        'country': country,
                        'open_source': open_source,
                        'company': company
                    })
                    if not tools_data[category]:
                        del tools_data[category]

                    if save_all_data(excel_file, tools_data, {}):  # 假设没有教程数据
                        st.success("修改已保存!")

        else:
            st.warning("该分类下没有条目可供编辑或删除!")

    elif operation == "增加分类":
        new_category = st.text_input("请输入新分类名称")
        if st.button("提交"):
            if new_category:
                if new_category not in tools_data:
                    tools_data[new_category] = []
                    save_all_data(excel_file, tools_data, {})
                    st.success(f"分类 '{new_category}' 已成功添加!")
                else:
                    st.error("该分类已存在,请选择其他名称。")
            else:
                st.error("分类名称不能为空。")

    elif operation == "删除分类":
        category = st.selectbox("选择分类", list(tools_data.keys()))
        if st.button("确认删除"):
            del tools_data[category]

            if save_all_data(excel_file, tools_data, {}):  # 假设没有教程数据
                st.success(f"分类 {category} 已删除!")


def main():
    # 从 Excel 文件读取工具数据
    excel_file = 'test.xlsx'
    tools_data = {}

    # 读取 Excel 文件内容
    df = pd.read_excel(excel_file, sheet_name='Tools')

    # 构建工具数据字典
    for _, row in df.iterrows():
        category = row['Category']
        if category not in tools_data:
            tools_data[category] = []
        tools_data[category].append({
            'name': row['Name'],
            'url': row['URL'],
            'description': row['Description'],
            'country': row['Country'],
            'open_source': row['Open Source'],
            'company': row['Company'],
            'popularity': row['Popularity'],
            'last_updated': row['LastUpdated']
        })

    data_management(excel_file, tools_data)


if __name__ == "__main__":
    main()

步骤 4:运行测试

将上述代码保存为 Python 文件,例如 data_management_app.py,然后在命令行中运行以下命令:

streamlit run data_management_app.py

验证输出

当应用启动后,你应该能够通过侧边栏操作来:

  • 进行分类质量检查
  • 添加、编辑和删除条目
  • 增加或删除分类

确保在每次操作后正确更新 Excel 文件,并在页面上显示相应的结果和消息。

注意事项

  1. Excel 文件路径:确保 Excel 文件路径正确或与脚本在同一目录下。
  2. 异常处理:在操作中添加异常处理以捕获错误。
  3. 数据有效性检查:确保用户输入的数据格式正确。

通过这些步骤,你应该能够测试 data_management 函数。如果有任何问题或进一步的要求,请随时告诉我!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/973591.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

matlab 车辆进出检测算法设计GUI界面-论文

1、内容简介 matlab151-车辆进出检测算法设计GUI界面-论文 可以交流、咨询、答疑 2、内容说明 略 随着科学技术的进步&#xff0c;社会的发展&#xff0c;各行各业都在发生着巨大的变化。近段时间以来&#xff0c;“无人化”智能产业正处于一个风口阶段&#xff0c;似乎我们…

python学习书籍推荐

### Python 学习路线图概述 为了有效地掌握Python这门编程语言并应用于不同领域&#xff0c;构建一个合理的学习路径至关重要。此学习路径不仅涵盖了基础语法&#xff0c;还深入到特定应用方向的关键技术。 #### 基础阶段 在这个初始阶段&#xff0c;重点在于理解Python的基…

基于Spring Boot的农事管理系统设计与实现(LW+源码+讲解)

专注于大学生项目实战开发,讲解,毕业答疑辅导&#xff0c;欢迎高校老师/同行前辈交流合作✌。 技术范围&#xff1a;SpringBoot、Vue、SSM、HLMT、小程序、Jsp、PHP、Nodejs、Python、爬虫、数据可视化、安卓app、大数据、物联网、机器学习等设计与开发。 主要内容&#xff1a;…

在 Ansys Motion 中创建链式伸缩臂的分步指南

介绍 链传动在负载和/或运动要远距离传递的机器中非常多产&#xff0c;例如&#xff0c;在两个平行轴之间。链条驱动系统的设计需要了解载荷传递和运动学如何影响链条张力、轴轴承中的悬臂载荷、轴应力和运动质量等。使用 Ansys Motion&#xff0c;可以轻松回答上述所有问题以…

Web Scraper,强大的浏览器爬虫插件!

Web Scraper是一款功能丰富的浏览器扩展爬虫工具&#xff0c;有着直观的图形界面&#xff0c;无需编写代码即可自定义数据抓取规则&#xff0c;高效地从网页中提取结构化数据&#xff0c;而且它支持灵活的数据导出选项&#xff0c;广泛应用于电商监控、内容聚合、市场调研等多元…

数据结构:栈和队列详解(下)

目录 一.如何用队列实现栈 1.思路&#xff1a; 2.具体代码&#xff1a; 二.如何用栈实现队列 1.思路&#xff1a; 2.具体代码&#xff1a; 一.如何用队列实现栈 原题来源&#xff1a;https://leetcode.cn/problems/implement-stack-using-queues/description/ 前言&#xf…

DeepSeek智能测试知识库助手PRO版:多格式支持+性能优化

前言 测试工程师在管理测试资产时,需要面对多种文档格式、大量文件分类及知识库的构建任务。为了解决这些问题,我们升级了 DeepSeek智能测试知识库助手,不仅支持更多文档格式,还加入了 多线程并发处理 和 可扩展格式支持,大幅提升处理性能和灵活性。 主要功能亮点: 多格…

宝塔面板开始ssl后,使用域名访问不了后台管理

宝塔面板后台开启ssl访问后&#xff0c;用的证书是其他第三方颁发的证书 再使用 域名/xxx 的形式&#xff1a;https://域名:xxx/xxx 访问后台&#xff0c;结果出现如下&#xff0c;不管使用 http 还是 https 的路径访问都进不后台管理 这个时候可以使用 https://ip/xxx 的方式来…

机器学习_12 逻辑回归知识点总结

逻辑回归是机器学习中一种重要的分类算法&#xff0c;广泛应用于二分类和多分类问题。它不仅能够预测分类结果&#xff0c;还能提供每个类别的概率估计。今天&#xff0c;我们就来深入探讨逻辑回归的原理、实现和应用。 一、逻辑回归的基本概念 1.1 逻辑回归与线性回归的区别…

AI Agent实战:打造京东广告主的超级助手 | 京东零售技术实践

前言 自2022年末ChatGPT的问世&#xff0c;大语言模型&#xff08;LLM&#xff09;技术引发全球关注。在大模型技术落地的最佳实践中&#xff0c;智能体&#xff08;Agent&#xff09;架构显现出巨大潜力&#xff0c;成为业界的普遍共识&#xff0c;各大公司也纷纷启动Agent技…

【工具篇】【深度解析 DeepAI 工具:开启 AI 应用新体验】

一、DeepAI 基本信息 嘿,咱先来说说 DeepAI 这工具到底是啥。DeepAI 是一个综合性的人工智能平台,就像是一个装满各种 AI 魔法的百宝箱。它把好多先进的人工智能技术整合到一起,让咱们普通人也能轻松用上这些高大上的 AI 功能。 这个平台背后有一群超厉害的技术人员,他们…

C语言之typedef

目录 前言 一、基本数据类型定义 二、作用 自带阅读 封装复杂类型的描述过程 三、指针类型定义 ​ 四、函数类型定义 总结 前言 typedef是C语言中用来为已有数据类型取别名的关键字。通过使用typedef关键字&#xff0c;可以方便地为数据类型定义新的名称&#xff0c;提高代码的…

如何在 SpringBoot 项目使用 Redis 的 Pipeline 功能

本文是博主在批量存储聊天中用户状态和登陆信息到 Redis 缓存中时&#xff0c;使用到了 Pipeline 功能&#xff0c;并对此做出了整理。 一、Redis Pipeline 是什么 Redis 的 Pipeline 功能可以显著提升 Redis 操作的性能&#xff0c;性能提升的原因在于可以批量执行命令。当我…

【HBase】HBaseJMX 接口监控信息实现钉钉告警

目录 一、JMX 简介 二、JMX监控信息钉钉告警实现 一、JMX 简介 官网&#xff1a;Apache HBase ™ Reference Guide JMX &#xff08;Java管理扩展&#xff09;提供了内置的工具&#xff0c;使您能够监视和管理Java VM。要启用远程系统的监视和管理&#xff0c;需要在启动Java…

鸿蒙开发环境搭建-入门篇

本文章讲述如何搭建鸿蒙应用开发环境&#xff1a;新建工程、虚拟机运行、真机调试等。 开发工具: DevEco Studio 5.0.3.906 os系统: mac 参考文档&#xff1a;https://juejin.cn/post/7356143704699699227 官网鸿蒙应用开发学习文档&#xff1a;https://developer.huawei.com/c…

[OD E 100] 生成哈夫曼树

题目 题目描述 给定长度为 n 的无序的数字数组&#xff0c;每个数字代表二叉树的叶子节点的权值&#xff0c;数字数组的值均大于等于 1 。请完成一个函数&#xff0c;根据输入的数字数组&#xff0c;生成哈夫曼树&#xff0c;并将哈夫曼树按照中序遍历输出。 为了保证输出的二…

Linux-ubuntu系统移植之Uboot启动流程

Linux-ubuntu系统移植之Uboot启动流程 一&#xff0c;Uboot启动流程1.Uboot的两阶段1.1.第一阶段1.11.硬件初始化1.12.复制 U-Boot 到 RAM1.13.跳转到第二阶段 1.2.第二阶段1.21.C 语言环境初始化1.22. 硬件设备初始化1.23. 加载环境变量1.24. 显示启动信息1.25. 等待用户输入&…

ElasticSearch公共方法封装

业务场景 1、RestClientBuilder初始化&#xff08;同时支持单机与集群&#xff09; 2、发送ES查询请求公共方法封装&#xff08;支持sql、kql、代理访问、集群访问、鉴权支持&#xff09; 3、判断ES索引是否存在&#xff08;/_cat/indices/${indexName}&#xff09; 4、判断ES…

vertical-align

属性名&#xff1a; vertical - align 。 作用&#xff1a;用于指定 同一行元素之间 &#xff0c;或 表格单元格 内文字的 垂直对齐方式 。 常用值&#xff1a; 1. baseline &#xff08;默认值&#xff09;&#xff1a;使元素的基线与父元素的基线对齐。 2. top …

Markdown 与富文本语法对照全解析

原文&#xff1a;Markdown 与富文本语法对照全解析 | w3cschool笔记 Markdown 和富文本是两种广泛应用的文本格式。Markdown 以简洁易读的语法著称&#xff0c;而富文本则凭借其丰富的样式和强大的功能深受用户喜爱。本文将对 Markdown 和富文本的语法进行详细对照&#xff0c…