SoFunction
Updated on 2025-05-17

Python Translation Dictionary Mini Program Function Description

1. Overview

This tool is an intelligent translation system developed based on Python. It uses Youdao dictionary for translation and has local dictionary cache and wordbook functions. Version number: v1.0 (2025-05-15)

2. Core function description

1. Basic translation functions

  • Instant translation: Enter English words to automatically obtain Chinese definition
  • Part of speech recognition: Automatically mark word part of words (noun/verb, etc.)
  • Network query: Get the latest dictionary data in real time
  • Offline query:For words that have been searched, first look up in the local SQLITE database.

2. Data storage system

  • Translation history
    • Automatically store all query records
    • Fields include: English words, Chinese definition, part of speech, query time
  • New word book management
    • Support manual addition/removal of new words
    • Arrange in reverse order of addition time
    • Independent database table storage collection relationship
"""
Small dictionary V1.0 
Copyright (C) 2025  Yang xiaofan 
    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 </licenses/>.
"""
import sqlite3
import requests
from bs4 import BeautifulSoup
def init_db():
    conn = ('')
    c = ()
    ('''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)''')
    # New new word list    ('''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))''')
    ()
    ()
def add_to_vocabulary(word):
    conn = ('')
    c = ()
    # Get word ID    ("SELECT id FROM translations WHERE english=?", (word,))
    word_id = ()
    if word_id:
        try:
            ("INSERT OR IGNORE INTO vocabulary_book (word_id) VALUES (?)", 
                     (word_id[0],))
            ()
            print(f"【{word}】Successfully added to the new word book")
        except :
            print(f"【{word}】Already in the new word book")
    else:
        print("Please query the word first to ensure it exists in the database")
    ()
def show_vocabulary():
    conn = ('')
    c = ()
    ('''SELECT , ,  
                 FROM translations t JOIN vocabulary_book v ON  = v.word_id
                 ORDER BY v.add_time DESC''')
    print("\n=== My new words book ===")
    for idx, (en, cn, pos) in enumerate((), 1):
        print(f"{idx}. {en} ({pos}): {cn}")
    ()
def save_to_db(english, chinese, pos):
    conn = ('')
    c = ()
    ("INSERT OR IGNORE INTO translations (english, chinese, pos) VALUES (?, ?, ?)",
              (english, chinese, pos))
    ()
    ()
def check_in_db(word):
    conn = ('')
    c = ()
    ("SELECT english, chinese, pos FROM translations WHERE english=?", (word,))
    result = ()
    ()
    return result if result else None
def translate_with_pos(word):
    # Check the local database first    db_result = check_in_db(word)
    if db_result:
        print(f"The word has been found in the local database, and the translation is as follows:")
        print(f"{db_result[0]} ({db_result[2]}): {db_result[1]}")
        choice = input("To continue network query, please enter w, please press Enter to exit directly:").strip().lower()
        if choice != 'w':
            return None
    url = f"/w/eng/{word}/"
    headers = {'User-Agent': 'Mozilla/5.0'}
    try:
        response = (url, headers=headers)
        soup = BeautifulSoup(, '')
        # Get Chinese definition        trans = ('div', class_='trans-container').get_text(strip=True)
        # Get part-of-speech annotation        pos_tag = ('span', class_='pos')
        pos = pos_tag.get_text() if pos_tag else "No part-of-word annotation"
        save_to_db(word, trans, pos)
        return f"{word} ({pos}): {trans}"
    except Exception as e:
        return f"Translation failed: {str(e)}"
if __name__ == "__main__":
    init_db()
    print("Command: \q Exit; \w Add to new word book \s View new word book \h View help")
    while True:
        query = input("Please enter English words or commands(enter\qquit): ").strip()
        if () == '\q':
            break
        if () == '\w':
            word = input("Enter the word you want to collect: ").strip()
            add_to_vocabulary(word)
            continue
        if () == '\s':
            show_vocabulary()
            continue
        if () == '\h':
            print("Command: \q Exit; \w Add to new word book \s View new word book \h View help")
            continue
        trans = translate_with_pos(query)
        if trans:
            print(f"-    {trans}")

Running example:

(.venv) D:\sanxia-src>
Order: \q quit;\w Add to new words \s View new word book \h View Help
请enterBritain文单词orOrder(enter\qquit): \s
=== My new words book ===
1. water (n.): n. water,雨water;water域,(River、river、lake、Sea, etc.)大片的water;(From a certain country)territorial sea,Sea area(waters);Unclear(Or unknown、difficulty、Danger, etc.)situation(waters);羊water(waters);(lake、The sea)water面;water位;Take a boat,走water路v. Give……浇water,irrigation;Give…...water喝,drink(animal);(Wind and other eyes)Tears;流口water;(Riverriver)流经并Give(A certain area)供water;加water冲淡,dilution【name】 (Water)(Britain)Walt(人name)[
                    plural
        waters
                     Third person odd number
        waters
                     Now parting words
        watering
                     Past tense
        watered
                     Past participle
        watered
                   ]
请enterBritain文单词orOrder(enter\qquit): yes
-    yes (n.): adv. yes,yes的n. yes(Show affirmation)[
                    plural
        yessesoryeses
                     Third person odd number
        yessesoryeses
                     Now parting words
        yessing
                     Past tense
        yessed
                     Past participle
        yessed
                   ]
请enterBritain文单词orOrder(enter\qquit): level
-    level (n.): n. quantity,degree;standard,water平;level,level;Look at it(or应对、understand)The way of things;water平高度,Relative height;floor;Flat floor;water平仪adj. Flat,water平的;The same value,The same status;The same score;Calm,Calmv. Make flat;Push down,Flatten;(make)Same score;(Especially with guns)aim;against……(Criticize, etc.);Stabilize,Reaching balance(level off);Meet honestly;作water准测量【name】 (Level)(Law)LeVer(人name)[
                    plural
        levels
                     Third person odd number
        levels
                     Now parting words
        levellingorleveling
                     Past tense
        levelledorleveled
                     Past participle
        levelledorleveled
                   ]
请enterBritain文单词orOrder(enter\qquit): jackfruit
-    jackfruit (n.): n. Wooden pineapple;jackfruit

This is the article about the function description of the Python translation dictionary applet. For more related Python translation dictionary content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!