我们将使用Python的tkinter库来创建一个简单的GUI应用程序。该程序将允许用户通过文本框输入查询,并从360百科网站抓取相关信息,然后显示在同一个文本框中。此外,程序还将支持从.txt文件读取输入,每次读取一行作为一次查询,并将所有查询及其结果保存到bata.txt文件中。
以下是完整的Python代码:
import tkinter as tk
from tkinter import filedialog
import requests
from bs4 import BeautifulSoup
import json
import os
class BaikeSearchApp:
def __init__(self, root):
self.root = root
self.root.title("360百科查询工具")
self.text = tk.Text(root, wrap='word', height=20, width=80)
self.text.pack(pady=10)
self.load_button = tk.Button(root, text="加载文件", command=self.load_file)
self.load_button.pack(side=tk.LEFT, padx=10)
self.query_button = tk.Button(root, text="获取回答", command=self.get_answer)
self.query_button.pack(side=tk.LEFT, padx=10)
self.save_button = tk.Button(root, text="保存记录", command=self.save_record)
self.save_button.pack(side=tk.LEFT, padx=10)
self.history = []
def load_file(self):
file_path = filedialog.askopenfilename(filetypes=[("Text files", "*.txt")])
if file_path:
with open(file_path, 'r', encoding='utf-8') as file:
for line in file:
self.text.insert(tk.END, f"问题: {line.strip()}\n")
self.get_answer(line.strip())
def get_answer(self, query=None):
if not query:
query = self.text.get("insert linestart", "insert lineend").strip()
if not query:
return
url = f"https://baike.so.com/doc?word={query}"
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
content = soup.find('meta', attrs={'name': 'description'})['content']
answer = {
"question": query,
"human_answers": [content],
"chatgpt_answers": [content]
}
self.text.insert(tk.END, json.dumps(answer, ensure_ascii=False) + "\n")
self.history.append(answer)
def save_record(self):
record_folder = "记录"
if not os.path.exists(record_folder):
os.makedirs(record_folder)
with open(os.path.join(record_folder, "bata.txt"), 'w', encoding='utf-8') as file:
for record in self.history:
file.write(json.dumps(record, ensure_ascii=False) + "\n")
if __name__ == "__main__":
root = tk.Tk()
app = BaikeSearchApp(root)
root.mainloop()
代码说明:
导入必要的库:
tkinter:用于创建GUI。
requests:用于发送HTTP请求。
BeautifulSoup:用于解析HTML。
json:用于处理JSON数据。
os:用于文件操作。
BaikeSearchApp类:
__init__方法:初始化GUI组件,包括文本框和按钮。
load_file方法:从文件中读取查询,并逐行处理。
get_answer方法:从360百科获取查询结果,并显示在文本框中。
save_record方法:将查询记录保存到bata.txt文件中。
主程序:
创建Tkinter窗口并启动应用程序。
运行步骤:
确保安装了requests和beautifulsoup4库:
pip install requests beautifulsoup4
将上述代码保存为一个Python文件(例如baike_search.py)。
运行该文件:
python baike_search.py
这样,您就可以通过GUI界面输入查询或加载文件中的查询,并查看和保存结果。