测试data_management函数

embedded/2025/2/22 10:37:39/

测试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 文件。以下是一个简单的示例实现:

python">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 文件并实现数据的管理功能:

python">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 Trueexcept Exception as e:st.error(f"保存失败:{str(e)}")return Falseclass 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 = 0for 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 += 1st.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 函数。如果有任何问题或进一步的要求,请随时告诉我!


http://www.ppmy.cn/embedded/164297.html

相关文章

华为最新OD机试真题-找单词-Python-OD统一考试(E卷)

最新华为OD机试考点合集:华为OD机试2024年真题题库(E卷+D卷+C卷)_华为od机试题库-CSDN博客 题目描述 给一个字符串和一个 二维字符数组,如果该字符串存在于该数组中,则按字符串的字符顺序输出字符串每个字符所在单元格的位置下标字符串,如果找不到返回字符串“N” 1.需…

深度学习模型应用场景全解析:CNN、Transformer、BERT、RNN与GAN

在深度学习的广阔天地里&#xff0c;各种模型如繁星点点&#xff0c;各自闪烁着独特的光芒。今天&#xff0c;让我们一同探索这些模型的适用场景、优势与局限&#xff0c;为您在模型选择时提供一份实用的指南。 一、卷积神经网络&#xff08;CNN&#xff09; CNN&#xff0c;…

python与pycharm如何设置文件夹为源代码根目录

python与pycharm如何设置文件夹为源代码根目录 前言 当我们在当前项目下引入了其它项目的代码&#xff0c;这是其它项目的包的导入路径是不用于当前项目的&#xff0c;这样导致项目无法正常起来&#xff0c;但是我们又不可能一个个文件去处理&#xff0c;这时可以用下面的方式…

Jmeter进阶篇(34)如何解决jmeter.save.saveservice.timestamp_format=ms报错?

问题描述 今天使用Jmeter完成压测执行,然后使用命令将jtl文件转换成html报告时,遇到了报错! 大致就是说jmeter里定义了一个jmeter.save.saveservice.timestamp_format=ms的时间格式,但是jtl文件中的时间格式不是标准的这个ms格式,导致无法正常解析。对于这个问题,有如下…

基于STM32单片机的智能蔬菜大棚温湿度监测系统设计

引言 在现代农业生产中&#xff0c;温湿度、光照强度和土壤湿度等环境因素对植物的生长起着至关重要的作用。智能蔬菜大棚正是基于这些因素&#xff0c;通过自动化控制和远程监控技术&#xff0c;实现对植物生长环境的精准管理&#xff0c;最终提升蔬菜的产量和质量。本文介绍…

C#上位机--结构

引言 在 C# 上位机开发中&#xff0c;我们常常需要处理各种数据&#xff0c;例如从硬件设备采集到的传感器数据、与下位机通信时传输的数据包等。结构&#xff08;struct&#xff09;作为 C# 中的一种值类型&#xff0c;在这种场景下有着广泛且重要的应用。它可以将多个相关的…

Fink与Hadoop的简介以及联系

Fink 和 Hadoop 是两个常用于大数据处理的开源工具&#xff0c;它们可以搭配使用以构建高效的数据处理系统。 一、Fink 和 Hadoop 的关系 Fink&#xff1a; 1、Fink 是一个分布式流处理框架&#xff0c;专注于实时数据处理。 它支持高吞吐、低延迟的流处理&#xff0c;适用于实…

JAVA学习-练习试用Java实现“使用Apache Flink对实时数据流进行复杂事件处理和筛查”

问题&#xff1a; 编写一个Java程序&#xff0c;使用Apache Flink对实时数据流进行复杂事件处理和筛查。 解答思路&#xff1a; Apache Flink 是一个流处理框架&#xff0c;非常适合进行实时数据流的复杂事件处理和筛查。以下是一个简单的Java程序示例&#xff0c;它展示了如何…