找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: 文档 工具 设计
查看: 12|回复: 0

一个简单的英语听写软件

[复制链接]

2万

主题

1547

回帖

3万

积分

超级版主

教育辅助界扛把子

附加身份标识
精华
1
热心
10
听众
1
威望
7
贡献
17231
违规
0
书币
55845
注册时间
2020-4-8

论坛元老灌水之王

发表于 2025-8-2 04:52 | 显示全部楼层 |阅读模式
做这个的原因是因为我徒弟不好好学习Java  单词也记不住 然后就给他写了一个听写软件
[AppleScript] 纯文本查看 复制代码
"""
单词听写软件 - 完整版
环境要求:
1. 安装必需库:在终端执行以下命令
   pip install pandas openpyxl
 
2. Excel文件要求:
   - 必须包含列:单词、释义、音标(区分大小写)
   - 至少包含一个以"day"命名的列(如day1/day2)
   - 文件保存为eng.xlsx,与程序同目录
"""
 
import pandas as pd
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import re
 
class DictationApp:
    def __init__(self, root):
        self.root = root
        self.root.title("小乔爱学习专用听写软件 v1.1")
        self.root.geometry("680x480")
         
        self.excel_file = None
        self.df = None
        self.days = []
         
        # 创建界面
        self.create_widgets()
        self.current_words = []
        self.current_index = 0
 
    def check_prerequisites(self, file_path=None):
        """检查运行环境要求"""
        errors = []
        file_to_check = file_path or self.excel_file
         
        if not file_to_check:
            return True
 
        # 检查文件存在性
        if not os.path.exists(file_to_check):
            errors.append("❌ 未找到Excel文件\n(请选择正确的文件)")
 
        # 检查文件可读性
        else:
            try:
                test_df = pd.read_excel(file_to_check, engine='openpyxl', nrows=1)
                required_columns = {'单词', '释义', '音标'}
                if not required_columns.issubset(test_df.columns):
                    missing = required_columns - set(test_df.columns)
                    errors.append(f"❌ 缺少必要列:{', '.join(missing)}")
            except Exception as e:
                errors.append(f"❌ 文件读取失败:{str(e)}")
 
        # 显示错误提示
        if errors:
            msg = "文件验证失败:\n\n" + "\n\n".join(errors) + \
                  "\n\n👉 请检查:\n1. 文件格式是否正确\n2. 是否被其他程序占用"
            messagebox.showerror("文件错误", msg)
            return False
        return True
 
    def load_data(self):
        """安全加载数据"""
        if not self.excel_file:
            return False
             
        try:
            self.df = pd.read_excel(self.excel_file, engine='openpyxl')
            # 从单词列中提取天数信息
            day_values = self.df['单词'].str.extract(r'(day\d+)', flags=re.IGNORECASE)
            self.days = sorted(list(set(day_values[0].dropna())))
            return True
        except Exception as e:
            messagebox.showerror("数据错误",
                                 f"数据加载失败:{str(e)}\n\n建议操作:\n1. 检查Excel格式\n2. 重新选择文件")
            return False
 
    def create_widgets(self):
        """创建界面组件"""
        # 主容器
        main_frame = ttk.Frame(self.root)
        main_frame.pack(fill="both", expand=True, padx=15, pady=15)
 
        # 左侧控制面板
        control_frame = ttk.LabelFrame(main_frame, text="控制面板", width=200)
        control_frame.pack(side="left", fill="y", padx=5, pady=5)
 
        # 文件选择按钮
        ttk.Button(control_frame, text="📂 选择文件",
                   command=self.select_file).pack(pady=5)
 
        # 天数选择区域
        self.days_frame = ttk.LabelFrame(control_frame, text="选择听写天数")
        self.days_frame.pack(fill="x", padx=5, pady=5)
         
        # 天数选择复选框(初始为空)
        self.day_vars = {}
 
        # 开始按钮
        self.start_btn = ttk.Button(control_frame, text="▶ 开始听写",
                                   command=self.start_dictation,
                                   state='disabled')
        self.start_btn.pack(pady=15)
 
        # 右侧听写区
        self.dictation_frame = ttk.LabelFrame(main_frame, text="听写区")
        self.dictation_frame.pack(side="right", fill="both", expand=True, padx=5, pady=5)
 
        # 听写组件
        self.chinese_label = ttk.Label(self.dictation_frame,
                                       text="请先选择Excel文件",
                                       font=("微软雅黑", 16), wraplength=400)
        self.chinese_label.pack(pady=20)
 
        self.entry = ttk.Entry(self.dictation_frame, font=("Consolas", 14))
        self.entry.pack(pady=10)
        self.entry.bind('<Return>', lambda e: self.check_answer())
 
        self.submit_btn = ttk.Button(self.dictation_frame,
                                     text="&#10003; 提交答案",
                                     command=self.check_answer)
        self.submit_btn.pack(pady=5)
 
        self.progress_label = ttk.Label(self.dictation_frame,
                                        text="等待选择文件...",
                                        font=("Arial", 10))
        self.progress_label.pack(pady=5)
 
        self.toggle_dictation_widgets(False)
 
    def select_file(self):
        """选择Excel文件"""
        file_path = filedialog.askopenfilename(
            title="选择Excel文件",
            filetypes=[("Excel文件", "*.xlsx")]
        )
         
        if file_path and self.check_prerequisites(file_path):
            self.excel_file = file_path
            if self.load_data():
                # 清空并重新创建天数选择区
                for widget in self.days_frame.winfo_children():
                    widget.destroy()
                self.day_vars.clear()
                 
                # 添加新的天数选择框
                for day in self.days:
                    self.day_vars[day] = tk.BooleanVar()
                    cb = ttk.Checkbutton(self.days_frame, text=day,
                                         variable=self.day_vars[day],
                                         onvalue=True, offvalue=False)
                    cb.pack(anchor="w", padx=5)
                 
                self.start_btn.config(state='normal')
                self.chinese_label.config(text="准备好后点击开始听写")
                self.progress_label.config(text="等待开始...")
 
    def toggle_dictation_widgets(self, active):
        """切换听写组件状态"""
        state = 'normal' if active else 'disabled'
        self.entry.config(state=state)
        self.submit_btn.config(state=state)
        self.entry.delete(0, 'end')
 
    def start_dictation(self):
        """开始听写流程"""
        selected_days = [day for day, var in self.day_vars.items() if var.get()]
        if not selected_days:
            messagebox.showwarning("选择错误", "请至少选择一个天数!")
            return
 
        # 合并所选天数的单词
        self.current_words = []
         
        # 获取DataFrame的所有索引
        all_indices = self.df.index.tolist()
         
        for day in selected_days:
            # 找到包含当前day标记的行的索引
            day_indices = self.df[self.df['单词'].str.contains(day, case=False, na=False)].index.tolist()
             
            for day_idx in day_indices:
                # 获取当前day标记后的索引,直到下一个day标记或结束
                next_idx = day_idx + 1
                while next_idx in all_indices:
                    current_word = self.df.iloc[next_idx]['单词']
                    # 如果遇到新的day标记,停止收集单词
                    if isinstance(current_word, str) and bool(re.search(r'day\d+', current_word, re.IGNORECASE)):
                        break
                    # 添加这个单词到听写列表
                    word_data = self.df.iloc[next_idx][['单词', '释义', '音标']].to_dict()
                    self.current_words.append(word_data)
                    next_idx += 1
 
        if not self.current_words:
            messagebox.showwarning("数据错误", "所选天数没有可用单词!")
            return
 
        self.current_index = 0
        self.toggle_dictation_widgets(True)
        self.show_current_word()
 
    def show_current_word(self):
        """显示当前单词"""
        if self.current_index >= len(self.current_words):
            messagebox.showinfo("完成", "&#127881; 所有单词听写完成!")
            self.toggle_dictation_widgets(False)
            return
 
        word = self.current_words[self.current_index]
        self.chinese_label.config(text=word['释义'])
        self.progress_label.config(
            text=f"进度:{self.current_index+1}/{len(self.current_words)}")
        self.entry.delete(0, 'end')
        self.entry.focus()
 
    def check_answer(self):
        """验证答案"""
        user_answer = self.entry.get().strip().lower()
        correct = self.current_words[self.current_index]['单词'].lower()
 
        if user_answer == correct:
            self.current_index += 1
            self.show_current_word()
        else:
            messagebox.showerror("错误",
                                 f"&#10006; 正确答案:{correct}\n"
                                 f"&#128266; 音标:{self.current_words[self.current_index]['音标']}")
            self.entry.delete(0, 'end')
 
def main():
    root = tk.Tk()
    app = DictationApp(root)
    root.mainloop()
 
if __name__ == '__main__':
    main()




QQ截图20250802045031.png QQ截图20250802045043.png



使用的时候只需要按照我的excel 拿过来 按照我的格式进行往下写就可以用了

我有成品 给你们放出来  你们也可以直接拿去代码  

下载:https://wwxe.lanzoub.com/ii2rM2oyebgh 密码:9n99


Great works are not done by strength, but by persistence! 历尽艰辛的飞升者,成了围剿孙悟空的十万天兵之一。
相信我 学习就是不断的重复 不需要什么技巧
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则 需要先绑定手机号


免责声明:
本站所发布的第三方软件及资源(包括但不仅限于文字/图片/音频/视频等仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢某程序或某个资源,请支持正版软件及版权方利益,注册或购买,得到更好的正版服务。如有侵权请邮件与我们联系处理。

Mail To: admin@cdsy.xyz

QQ|Archiver|手机版|小黑屋|城东书院 ( 湘ICP备19021508号-1|湘公网安备 43102202000103号 )

GMT+8, 2025-8-16 22:04 , Processed in 0.051391 second(s), 31 queries .

Powered by Discuz! CDSY.XYZ

Copyright © 2019-2025, Tencent Cloud.

快速回复 返回顶部 返回列表