Python 翻译词典小程序

一、概述

本工具是基于Python开发的智能翻译系统,采用有道词典进行翻译,并具有本地词典缓存以及单词本功能。 版本号:v1.0 (2025-05-15)

二、核心功能说明

1. 基础翻译功能

  • 即时翻译:输入英文单词自动获取中文释义

  • 词性识别:自动标注单词词性(名词/动词等)

  • 网络查询:实时获取最新词典数据

  • 离线查询: 对以查过的单词,首先在本地SQLITE数据库查找

2. 数据存储系统

  • 翻译历史

    • 自动存储所有查询记录

    • 字段包含:英文单词、中文释义、词性、查询时间

  • 生词本管理

    • 支持手动添加/移除生词

    • 按添加时间倒序排列

    • 独立数据库表存储收藏关系

      python 复制代码
      """
      小小词典 V1.0 
      Copyright (C) 2025  yoyo
      
          This program is free software: you can redistribute it and/or modify
          it under the terms of the GNU General Public License as published by
          the Free Software Foundation, either version 3 of the License, or
          (at your option) any later version.
      
          This program is distributed in the hope that it will be useful,
          but WITHOUT ANY WARRANTY; without even the implied warranty of
          MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
          GNU General Public License for more details.
      
          You should have received a copy of the GNU General Public License
          along with this program.  If not, see <https://www.gnu.org/licenses/>.
      """
      import sqlite3
      import requests
      from bs4 import BeautifulSoup
      
      def init_db():
          conn = sqlite3.connect('translations.db')
          c = conn.cursor()
          c.execute('''CREATE TABLE IF NOT EXISTS translations
                       (id INTEGER PRIMARY KEY AUTOINCREMENT,
                        english TEXT UNIQUE NOT NULL,
                        chinese TEXT NOT NULL,
                        pos TEXT,
                        create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')
          # 新增生词本表
          c.execute('''CREATE TABLE IF NOT EXISTS vocabulary_book
                       (id INTEGER PRIMARY KEY AUTOINCREMENT,
                        word_id INTEGER UNIQUE,
                        add_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                        FOREIGN KEY(word_id) REFERENCES translations(id))''')
          conn.commit()
          conn.close()
          
      def add_to_vocabulary(word):
          conn = sqlite3.connect('translations.db')
          c = conn.cursor()
          # 获取单词ID
          c.execute("SELECT id FROM translations WHERE english=?", (word,))
          word_id = c.fetchone()
          if word_id:
              try:
                  c.execute("INSERT OR IGNORE INTO vocabulary_book (word_id) VALUES (?)", 
                           (word_id[0],))
                  conn.commit()
                  print(f"【{word}】已成功加入生词本")
              except sqlite3.IntegrityError:
                  print(f"【{word}】已在生词本中")
          else:
              print("请先查询该单词确保其存在于数据库")
          conn.close()
      
      def show_vocabulary():
          conn = sqlite3.connect('translations.db')
          c = conn.cursor()
          c.execute('''SELECT t.english, t.chinese, t.pos 
                       FROM translations t JOIN vocabulary_book v ON t.id = v.word_id
                       ORDER BY v.add_time DESC''')
          print("\n=== 我的生词本 ===")
          for idx, (en, cn, pos) in enumerate(c.fetchall(), 1):
              print(f"{idx}. {en} ({pos}): {cn}")
          conn.close()
          
      def save_to_db(english, chinese, pos):
          conn = sqlite3.connect('translations.db')
          c = conn.cursor()
          c.execute("INSERT OR IGNORE INTO translations (english, chinese, pos) VALUES (?, ?, ?)",
                    (english, chinese, pos))
          conn.commit()
          conn.close()
          
      def check_in_db(word):
          conn = sqlite3.connect('translations.db')
          c = conn.cursor()
          c.execute("SELECT english, chinese, pos FROM translations WHERE english=?", (word,))
          result = c.fetchone()
          conn.close()
          return result if result else None
          
      def translate_with_pos(word):
          # 先查本地数据库
          db_result = check_in_db(word)
          if db_result:
              print(f"该单词已在本地数据库查找到,翻译解释如下:")
              print(f"{db_result[0]} ({db_result[2]}): {db_result[1]}")
              choice = input("继续网络查询请输入w,直接退出请按回车:").strip().lower()
              if choice != 'w':
                  return None
          url = f"https://dict.youdao.com/w/eng/{word}/"
          headers = {'User-Agent': 'Mozilla/5.0'}
          
          try:
              response = requests.get(url, headers=headers)
              soup = BeautifulSoup(response.text, 'html.parser')
              
              # 获取中文释义
              trans = soup.find('div', class_='trans-container').get_text(strip=True)
              
              # 获取词性标注
              pos_tag = soup.find('span', class_='pos')
              pos = pos_tag.get_text() if pos_tag else "无词性标注"
              save_to_db(word, trans, pos)
              return f"{word} ({pos}): {trans}"
          except Exception as e:
              return f"翻译失败: {str(e)}"
      
      if __name__ == "__main__":
          init_db()
          print("命令: \q 退出;\w 加入生词本 \s 查看生词本 \h 查看帮助")
          while True:
              query = input("请输入英文单词或命令(输入\q退出): ").strip()
              if query.lower() == '\q':
                  break
              if query.lower() == '\w':
                  word = input("输入要收藏的单词: ").strip()
                  add_to_vocabulary(word)
                  continue
              if query.lower() == '\s':
                  show_vocabulary()
                  continue
              if query.lower() == '\h':
                  print("命令: \q 退出;\w 加入生词本 \s 查看生词本 \h 查看帮助")
                  continue
              trans = translate_with_pos(query)
              if trans:
                  print(f"-    {trans}")

      运行实例:

    cpp 复制代码
    (.venv) D:\sanxia-src>translate.py
    命令: \q 退出;\w 加入生词本 \s 查看生词本 \h 查看帮助
    请输入英文单词或命令(输入\q退出): \s
    
    === 我的生词本 ===
    1. water (n.): n. 水,雨水;水域,(江、河、湖、海等)大片的水;(某个国家的)领海,海域(waters);不明朗(或未知的、困难、危险等)局面(waters);羊水(waters);(湖、海的)水面;水位;乘船,走水路v. 给......浇水,灌溉;给......水喝,饮(动物);(风等使眼睛)流泪;流口水;(江河)流经并给(某地区)供水;加水冲淡,稀释【名】 (Water)(英)沃特(人名)[
                        复数
            waters
                         第三人称单数
            waters
                         现在分词
            watering
                         过去式
            watered
                         过去分词
            watered
                       ]
    请输入英文单词或命令(输入\q退出): yes
    -    yes (n.): adv. 是,是的n. 是(表示肯定)[
                        复数
            yesses或yeses
                         第三人称单数
            yesses或yeses
                         现在分词
            yessing
                         过去式
            yessed
                         过去分词
            yessed
                       ]
    请输入英文单词或命令(输入\q退出): level
    -    level (n.): n. 数量,程度;标准,水平;层次,级别;看待(或应对、理解)事物的方式;水平高度,相对高度;楼层;平地;水平仪adj. 平坦的,水平的;相同价值的,相同地位的;比分相同的;平静的,冷静的v. 使平整;推倒,夷平;(使)比分相同;(尤指用枪)瞄准;针对......(进行批评等);稳定下来,达到平衡(level off);坦诚相见;作水准测量【名】 (Level)(法)勒韦尔(人名)[
                        复数
            levels
                         第三人称单数
            levels
                         现在分词
            levelling或leveling
                         过去式
            levelled或leveled
                         过去分词
            levelled或leveled
                       ]
    请输入英文单词或命令(输入\q退出): jackfruit
    -    jackfruit (n.): n. 木菠萝;菠萝蜜
相关推荐
andrsted21 分钟前
用练题簿小程序 - 让错题不再白错
学习·微信小程序·小程序·学习方法
2601_9499506327 分钟前
练题簿,把培训从“走过场”变成“真落地”
人工智能·学习·小程序·刷题·小程序推荐
疯狂小猫咪1 小时前
中小培训机构教务数字化踩坑复盘|从 Excel 过渡到教务系统经验总结
小程序·excel
问天_观心4 小时前
大模型微调学习(二)
人工智能·python·深度学习·学习·语言模型·transformer
洋洋不叫杨杨4 小时前
揭秘当下知名的SEO优化渠道,你知道几个?
大数据·python
阿童木写作4 小时前
跨境图片翻译工具推荐:批量处理视频字幕与智能抠图
python·音视频
梦想的颜色4 小时前
OCR 识别原理与 Python 识图全实战:从文字提取到图像内容理解
python·计算机视觉·ocr·图像识别·python 识图
禹凕4 小时前
Dijkstra算法详解与应用
python·算法
别走!万哥爱你5 小时前
Python 中可以用于在已排序的列表中查找特定元素的位置的是什么?
python
wxwx_bscxy3226 小时前
基于Python新冠疫情可视化分析系统的设计与实现
java·数据库·spring boot·python·微信小程序·sqlite