宠物网站项目,南京时事重大新闻,哪个网站是专门为建设方服务的,安卓市场下载安装对数据集搜集器#xff08;百科#xff09;007进行一下改进#xff1a; 错误处理#xff1a;增加更多的错误处理#xff0c;比如网络请求超时、解析错误等。 用户界面#xff1a;增加一些提示信息#xff0c;让用户更清楚当前的操作状态。 多线程处理#xff1a;确保多…对数据集搜集器百科007进行一下改进 错误处理增加更多的错误处理比如网络请求超时、解析错误等。 用户界面增加一些提示信息让用户更清楚当前的操作状态。 多线程处理确保多线程处理更加安全避免多个线程同时操作同一资源。 日志记录增加更多的日志记录方便调试和追踪问题。 配置文件引入配置文件方便修改一些常量如记录文件夹名称。 完善后的代码 python
import tkinter as tk
from tkinter import filedialog, messagebox
import requests
from bs4 import BeautifulSoup
import json
import os
import threading
from tkinter import ttk
import logging# 配置日志
logging.basicConfig(filenameapp.log, levellogging.INFO, format%(asctime)s - %(levelname)s - %(message)s)# 读取配置文件
CONFIG_FILE config.json
DEFAULT_CONFIG {record_folder: 记录,log_file: app.log
}def load_config():if os.path.exists(CONFIG_FILE):with open(CONFIG_FILE, r, encodingutf-8) as file:return json.load(file)return DEFAULT_CONFIGconfig load_config()class BaikeSearchApp:def __init__(self, root):self.root rootself.root.title(百度百科查询工具)# 创建输入框self.input_label tk.Label(root, text输入问题:)self.input_label.pack(pady5)self.input_entry tk.Entry(root, width80)self.input_entry.pack(pady5)# 创建文本框self.text tk.Text(root, wrapword, height20, width80)self.text.pack(pady10)# 创建按钮self.load_button tk.Button(root, text加载文件, commandself.load_file)self.load_button.pack(sidetk.LEFT, padx10)self.query_button tk.Button(root, text获取回答, commandself.get_answer)self.query_button.pack(sidetk.LEFT, padx10)self.save_button tk.Button(root, text保存记录, commandself.save_record)self.save_button.pack(sidetk.LEFT, padx10)self.history_button tk.Button(root, text查看历史记录, commandself.show_history)self.history_button.pack(sidetk.LEFT, padx10)self.help_button tk.Button(root, text帮助, commandself.show_help)self.help_button.pack(sidetk.LEFT, padx10)# 创建状态栏self.status_var tk.StringVar()self.status_bar tk.Label(root, textvariableself.status_var, bd1, relieftk.SUNKEN, anchortk.W)self.status_bar.pack(sidetk.BOTTOM, filltk.X)# 创建进度条self.progress ttk.Progressbar(root, orienthorizontal, length300, modedeterminate)self.progress.pack(pady10)# 初始化历史记录self.history []self.root.protocol(WM_DELETE_WINDOW, self.on_closing)def on_closing(self):if hasattr(self, thread) and self.thread.is_alive():messagebox.showinfo(提示, 请等待所有任务完成后再关闭窗口。)else:self.root.destroy()def load_file(self):file_path filedialog.askopenfilename(filetypes[(Text files, *.txt)])if file_path:with open(file_path, r, encodingutf-8) as file:lines file.readlines()total_lines len(lines)self.progress[maximum] total_linesfor i, line in enumerate(lines):self.text.insert(tk.END, f问题: {line.strip()}\n)self.get_answer(line.strip())self.progress[value] i 1self.root.update_idletasks()self.status_var.set(f已加载文件: {file_path})def get_answer(self, queryNone):if not query:query self.input_entry.get().strip()if not query:query self.text.get(insert linestart, insert lineend).strip()if not query:messagebox.showwarning(警告, 请先输入或选择一个问题)returnself.status_var.set(f正在查询: {query})logging.info(f开始查询: {query})self.thread threading.Thread(targetself._get_answer, args(query,))self.thread.start()def _get_answer(self, query):url fhttps://baike.baidu.com/item/{query}try:response requests.get(url, timeout10)response.raise_for_status()soup BeautifulSoup(response.content, html.parser)# 从meta标签中提取描述description_tag soup.find(meta, attrs{name: description})if description_tag and content in description_tag.attrs:content description_tag[content]else:content 未找到相关词条answer {question: query,human_answers: [content],chatgpt_answers: [content]}formatted_answer f问题: {query}\n答案: {content}\n\nself.text.insert(tk.END, formatted_answer)self.history.append(answer)self.status_var.set(f查询完成: {query})logging.info(f查询完成: {query})except requests.RequestException as e:self.text.insert(tk.END, f请求失败: {e}\n)self.status_var.set(请求失败)logging.error(f请求失败: {e})def save_record(self):record_folder config[record_folder]if not os.path.exists(record_folder):os.makedirs(record_folder)with open(os.path.join(record_folder, bata.txt), w, encodingutf-8) as file:for record in self.history:file.write(json.dumps(record, ensure_asciiFalse) \n)self.status_var.set(记录已保存)def show_history(self):history_window tk.Toplevel(self.root)history_window.title(历史记录)history_text tk.Text(history_window, wrapword, height20, width80)history_text.pack(pady10)for record in self.history:history_text.insert(tk.END, json.dumps(record, ensure_asciiFalse) \n)clear_button tk.Button(history_window, text清空历史记录, commandself.clear_history)clear_button.pack(pady10)def clear_history(self):self.history []self.text.delete(1.0, tk.END)self.status_var.set(历史记录已清空)def show_help(self):help_window tk.Toplevel(self.root)help_window.title(帮助文档)help_text tk.Text(help_window, wrapword, height20, width80)help_text.pack(pady10)help_content 使用说明:1. 在输入框中输入问题点击“获取回答”按钮查询答案。2. 点击“加载文件”按钮选择包含问题的文本文件批量查询答案。3. 查询结果会显示在文本框中并自动保存到历史记录。4. 点击“保存记录”按钮将历史记录保存到文件中。5. 点击“查看历史记录”按钮查看和管理历史记录。6. 点击“帮助”按钮查看使用说明。help_text.insert(tk.END, help_content)if __name__ __main__:root tk.Tk()app BaikeSearchApp(root)root.mainloop()主要改进点
配置文件引入了 config.json 文件来存储一些常量如记录文件夹名称。 错误处理增加了网络请求的超时处理。 日志记录增加了更多的日志记录方便调试和追踪问题。 用户界面增加了更多的状态提示让用户更清楚当前的操作状态。