Certainly! I can help you create a Windows GUI application using Python's Tkinter library. This application will allow you to select an HTML file, extract the MWQUIZ questions and answers, and display them in a user-friendly interface.
Here's a step-by-step guide along with the complete Python code:
Step 1: Prerequisites
-
Python Installation:
- Ensure you have Python installed on your Windows machine. You can download it from python.org.
- During installation, make sure to check the option "Add Python to PATH".
-
Libraries:
- The script uses standard Python libraries (
re, tkinter, and tkinter.filedialog), so no additional installations are required.
Step 2: The Complete Python Script
import re
import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext
def extract_mwquiz_from_html(content):
"""
Extracts MWQUIZ questions and answers from the provided HTML content.
Args:
content (str): The HTML content as a string.
Returns:
list of tuples: A list where each tuple contains a question and its corresponding answer.
"""
# Find the MWQUIZ variable
mwquiz_match = re.search(r'var\s+MWQUIZ\s*=\s*(\{.*?\});', content, re.DOTALL)
if not mwquiz_match:
return None
mwquiz_str = mwquiz_match.group(1)
# Extract questions and answers
questions = re.findall(r'"question"\s*:\s*"([^"]*?)"', mwquiz_str)
answers = re.findall(r'"is_correct"\s*:\s*1\s*,\s*"answer"\s*:\s*"([^"]*?)"', mwquiz_str)
return list(zip(questions, answers))
def open_file():
"""
Opens a file dialog for the user to select an HTML file and processes it.
"""
file_path = filedialog.askopenfilename(
title="Select HTML File",
filetypes=[("HTML Files", "*.html *.htm"), ("All Files", "*.*")]
)
if file_path:
try:
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
qa_pairs = extract_mwquiz_from_html(content)
if qa_pairs:
display_results(qa_pairs)
else:
messagebox.showwarning("No MWQUIZ Found", "The MWQUIZ variable was not found in the selected HTML file.")
except Exception as e:
messagebox.showerror("Error", f"An error occurred:\n{e}")
def display_results(qa_pairs):
"""
Displays the extracted questions and answers in the text area.
Args:
qa_pairs (list of tuples): The list of question-answer pairs.
"""
text_area.config(state='normal')
text_area.delete(1.0, tk.END)
for i, (question, answer) in enumerate(qa_pairs, 1):
text_area.insert(tk.END, f"Q{i}: {question}\nA{i}: {answer}\n\n")
text_area.config(state='disabled')
def create_gui():
"""
Creates and runs the Tkinter GUI application.
"""
global text_area
root = tk.Tk()
root.title("MWQUIZ Extractor")
root.geometry("800x600")
root.resizable(True, True)
# Create a menu
menubar = tk.Menu(root)
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="Open HTML File", command=open_file)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
# Create a toolbar with an open button
toolbar = tk.Frame(root, bd=1, relief=tk.RAISED)
open_icon = tk.PhotoImage(width=1, height=1) # Placeholder for icon
open_button = tk.Button(toolbar, text="Open HTML File", relief=tk.FLAT, command=open_file)
open_button.pack(side=tk.LEFT, padx=2, pady=2)
toolbar.pack(side=tk.TOP, fill=tk.X)
# Create a scrolled text area to display results
text_area = scrolledtext.ScrolledText(root, wrap=tk.WORD, font=("Arial", 12), state='disabled')
text_area.pack(expand=True, fill='both', padx=10, pady=10)
# Instruction label
instruction = tk.Label(root, text="Use the 'File' menu or the 'Open HTML File' button to select an HTML file.", font=("Arial", 10))
instruction.pack(pady=(0,10))
root.mainloop()
if __name__ == "__main__":
create_gui()
Step 3: Understanding the Script
-
Function extract_mwquiz_from_html:
- Uses regular expressions to locate the
MWQUIZ JavaScript variable in the HTML content.
- Extracts all questions and their corresponding correct answers.
- Returns a list of tuples containing question-answer pairs.
-
Function open_file:
- Opens a file dialog for the user to select an HTML file.
- Reads the selected file and extracts the Q&A pairs using
extract_mwquiz_from_html.
- Handles cases where
MWQUIZ is not found or if there's an error during file reading.
-
Function display_results:
- Takes the extracted Q&A pairs and displays them in a scrollable text area within the GUI.
-
Function create_gui:
- Sets up the main window using Tkinter.
- Adds a menu bar with options to open an HTML file or exit the application.
- Adds a toolbar with an "Open HTML File" button for quick access.
- Includes a scrollable text area to display the results.
- Provides an instruction label for user guidance.
Step 4: Running the Application
-
Save the Script:
- Save the provided Python script to a file, e.g.,
mwquiz_extractor_gui.py.
-
Run the Script:
-
Open Command Prompt.
-
Navigate to the directory where you saved the script.
-
Execute the script using Python:
python mwquiz_extractor_gui.py
-
Using the Application:
- Open HTML File:
- Click on
File > Open HTML File from the menu or click the "Open HTML File" button on the toolbar.
- Browse and select your HTML file containing the
MWQUIZ variable.
- View Results:
- After selecting a valid file, the extracted questions and answers will be displayed in the text area.
- Error Handling:
- If
MWQUIZ is not found or there's an error reading the file, appropriate warning or error messages will be shown.
Optional: Creating an Executable for Easier Use
If you'd like to run the application without needing to have Python installed, you can convert the script into a standalone executable using PyInstaller. Here's how:
-
Install PyInstaller:
pip install pyinstaller
-
Create the Executable:
pyinstaller --onefile --windowed mwquiz_extractor_gui.py
- The
--onefile option packages everything into a single executable.
- The
--windowed option ensures no console window appears when running the app.
-
Locate the Executable:
- After the process completes, you'll find the
mwquiz_extractor_gui.exe in the dist folder within your project directory.
-
Run the Executable:
- You can now run the
.exe file on any Windows machine without needing Python installed.
Final Notes
-
Customization:
- You can enhance the GUI by adding features like saving the extracted Q&As to a file (e.g., CSV, TXT).
- Implementing better icons and aesthetics can make the application more user-friendly.
-
Error Handling:
- The script includes basic error handling. Depending on your HTML's structure, you might need to adjust the regular expressions for more complex scenarios.
-
Extensibility:
- If you need to support more data extraction features in the future, consider using more robust HTML parsing libraries like
BeautifulSoup.
Feel free to customize the application further based on your specific needs. If you encounter any issues or have additional questions, don't hesitate to ask!