数据集搜集器(百科)008

打印 上一主题 下一主题

主题 1026|帖子 1026|积分 3078

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
对数据集搜集器(百科)007进行一下改进:
错误处理:增长更多的错误处理,比如网络请求超时、剖析错误等。
用户界面:增长一些提示信息,让用户更清楚当前的操纵状态。
多线程处理:确保多线程处理更加安全,避免多个线程同时操纵同一资源。
日志记录:增长更多的日志记录,方便调试和追踪题目。
设置文件:引入设置文件,方便修改一些常量(如记录文件夹名称)。
完善后的代码
python
  1. import tkinter as tk
  2. from tkinter import filedialog, messagebox
  3. import requests
  4. from bs4 import BeautifulSoup
  5. import json
  6. import os
  7. import threading
  8. from tkinter import ttk
  9. import logging
  10. # 配置日志
  11. logging.basicConfig(filename='app.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  12. # 读取配置文件
  13. CONFIG_FILE = 'config.json'
  14. DEFAULT_CONFIG = {
  15.     "record_folder": "记录",
  16.     "log_file": "app.log"
  17. }
  18. def load_config():
  19.     if os.path.exists(CONFIG_FILE):
  20.         with open(CONFIG_FILE, 'r', encoding='utf-8') as file:
  21.             return json.load(file)
  22.     return DEFAULT_CONFIG
  23. config = load_config()
  24. class BaikeSearchApp:
  25.     def __init__(self, root):
  26.         self.root = root
  27.         self.root.title("百度百科查询工具")
  28.         # 创建输入框
  29.         self.input_label = tk.Label(root, text="输入问题:")
  30.         self.input_label.pack(pady=5)
  31.         self.input_entry = tk.Entry(root, width=80)
  32.         self.input_entry.pack(pady=5)
  33.         # 创建文本框
  34.         self.text = tk.Text(root, wrap='word', height=20, width=80)
  35.         self.text.pack(pady=10)
  36.         # 创建按钮
  37.         self.load_button = tk.Button(root, text="加载文件", command=self.load_file)
  38.         self.load_button.pack(side=tk.LEFT, padx=10)
  39.         self.query_button = tk.Button(root, text="获取回答", command=self.get_answer)
  40.         self.query_button.pack(side=tk.LEFT, padx=10)
  41.         self.save_button = tk.Button(root, text="保存记录", command=self.save_record)
  42.         self.save_button.pack(side=tk.LEFT, padx=10)
  43.         self.history_button = tk.Button(root, text="查看历史记录", command=self.show_history)
  44.         self.history_button.pack(side=tk.LEFT, padx=10)
  45.         self.help_button = tk.Button(root, text="帮助", command=self.show_help)
  46.         self.help_button.pack(side=tk.LEFT, padx=10)
  47.         # 创建状态栏
  48.         self.status_var = tk.StringVar()
  49.         self.status_bar = tk.Label(root, textvariable=self.status_var, bd=1, relief=tk.SUNKEN, anchor=tk.W)
  50.         self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
  51.         # 创建进度条
  52.         self.progress = ttk.Progressbar(root, orient="horizontal", length=300, mode="determinate")
  53.         self.progress.pack(pady=10)
  54.         # 初始化历史记录
  55.         self.history = []
  56.         self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
  57.     def on_closing(self):
  58.         if hasattr(self, 'thread') and self.thread.is_alive():
  59.             messagebox.showinfo("提示", "请等待所有任务完成后再关闭窗口。")
  60.         else:
  61.             self.root.destroy()
  62.     def load_file(self):
  63.         file_path = filedialog.askopenfilename(filetypes=[("Text files", "*.txt")])
  64.         if file_path:
  65.             with open(file_path, 'r', encoding='utf-8') as file:
  66.                 lines = file.readlines()
  67.                 total_lines = len(lines)
  68.                 self.progress["maximum"] = total_lines
  69.                 for i, line in enumerate(lines):
  70.                     self.text.insert(tk.END, f"问题: {line.strip()}\n")
  71.                     self.get_answer(line.strip())
  72.                     self.progress["value"] = i + 1
  73.                     self.root.update_idletasks()
  74.             self.status_var.set(f"已加载文件: {file_path}")
  75.     def get_answer(self, query=None):
  76.         if not query:
  77.             query = self.input_entry.get().strip()
  78.             if not query:
  79.                 query = self.text.get("insert linestart", "insert lineend").strip()
  80.             if not query:
  81.                 messagebox.showwarning("警告", "请先输入或选择一个问题")
  82.                 return
  83.         self.status_var.set(f"正在查询: {query}")
  84.         logging.info(f"开始查询: {query}")
  85.         self.thread = threading.Thread(target=self._get_answer, args=(query,))
  86.         self.thread.start()
  87.     def _get_answer(self, query):
  88.         url = f"https://baike.baidu.com/item/{query}"
  89.         try:
  90.             response = requests.get(url, timeout=10)
  91.             response.raise_for_status()
  92.             soup = BeautifulSoup(response.content, 'html.parser')
  93.             # 从<meta>标签中提取描述
  94.             description_tag = soup.find('meta', attrs={'name': 'description'})
  95.             if description_tag and 'content' in description_tag.attrs:
  96.                 content = description_tag['content']
  97.             else:
  98.                 content = "未找到相关词条"
  99.             answer = {
  100.                 "question": query,
  101.                 "human_answers": [content],
  102.                 "chatgpt_answers": [content]
  103.             }
  104.             formatted_answer = f"问题: {query}\n答案: {content}\n\n"
  105.             self.text.insert(tk.END, formatted_answer)
  106.             self.history.append(answer)
  107.             self.status_var.set(f"查询完成: {query}")
  108.             logging.info(f"查询完成: {query}")
  109.         except requests.RequestException as e:
  110.             self.text.insert(tk.END, f"请求失败: {e}\n")
  111.             self.status_var.set("请求失败")
  112.             logging.error(f"请求失败: {e}")
  113.     def save_record(self):
  114.         record_folder = config["record_folder"]
  115.         if not os.path.exists(record_folder):
  116.             os.makedirs(record_folder)
  117.         with open(os.path.join(record_folder, "bata.txt"), 'w', encoding='utf-8') as file:
  118.             for record in self.history:
  119.                 file.write(json.dumps(record, ensure_ascii=False) + "\n")
  120.         self.status_var.set("记录已保存")
  121.     def show_history(self):
  122.         history_window = tk.Toplevel(self.root)
  123.         history_window.title("历史记录")
  124.         history_text = tk.Text(history_window, wrap='word', height=20, width=80)
  125.         history_text.pack(pady=10)
  126.         for record in self.history:
  127.             history_text.insert(tk.END, json.dumps(record, ensure_ascii=False) + "\n")
  128.         clear_button = tk.Button(history_window, text="清空历史记录", command=self.clear_history)
  129.         clear_button.pack(pady=10)
  130.     def clear_history(self):
  131.         self.history = []
  132.         self.text.delete(1.0, tk.END)
  133.         self.status_var.set("历史记录已清空")
  134.     def show_help(self):
  135.         help_window = tk.Toplevel(self.root)
  136.         help_window.title("帮助文档")
  137.         help_text = tk.Text(help_window, wrap='word', height=20, width=80)
  138.         help_text.pack(pady=10)
  139.         help_content = """
  140.         使用说明:
  141.         1. 在输入框中输入问题,点击“获取回答”按钮查询答案。
  142.         2. 点击“加载文件”按钮,选择包含问题的文本文件,批量查询答案。
  143.         3. 查询结果会显示在文本框中,并自动保存到历史记录。
  144.         4. 点击“保存记录”按钮,将历史记录保存到文件中。
  145.         5. 点击“查看历史记录”按钮,查看和管理历史记录。
  146.         6. 点击“帮助”按钮,查看使用说明。
  147.         """
  148.         help_text.insert(tk.END, help_content)
  149. if __name__ == "__main__":
  150.     root = tk.Tk()
  151.     app = BaikeSearchApp(root)
  152.     root.mainloop()
复制代码
重要改进点

设置文件:引入了 config.json 文件来存储一些常量,如记录文件夹名称。
错误处理:增长了网络请求的超时处理。
日志记录:增长了更多的日志记录,方便调试和追踪题目。
用户界面:增长了更多的状态提示,让用户更清楚当前的操纵状态。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

立聪堂德州十三局店

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表