Python实现墨墨背单词的查词典功能

墨墨有点非常好,单词可以查很多知名在线词典的释义,排版都不错,除了词源那个不能适应手机。想问问原理,自己尝试搞一下
Python实现墨墨背单词的查词典功能

6 回复

好巧,我也在用


我理解你想用Python实现类似墨墨背单词的查词典功能。核心思路是获取单词数据(本地或在线API),然后解析和展示。

这里提供一个完整的本地词典实现方案,使用json存储数据,difflib提供模糊匹配:

import json
import os
import difflib
from typing import Dict, Optional

class LocalDictionary:
    def __init__(self, dict_file: str = "dictionary.json"):
        self.dict_file = dict_file
        self.dictionary = self._load_dictionary()
    
    def _load_dictionary(self) -> Dict:
        """加载词典数据"""
        if os.path.exists(self.dict_file):
            with open(self.dict_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        else:
            # 示例数据,实际可替换为完整词典
            sample_data = {
                "hello": {
                    "phonetic": "/həˈləʊ/",
                    "meanings": ["int. 喂;你好", "n. 问候"],
                    "examples": ["Hello, how are you?", "Say hello to your mother."]
                },
                "python": {
                    "phonetic": "/ˈpaɪθən/",
                    "meanings": ["n. 蟒蛇", "n. Python编程语言"],
                    "examples": ["Python is a powerful programming language."]
                }
            }
            self._save_dictionary(sample_data)
            return sample_data
    
    def _save_dictionary(self, data: Dict):
        """保存词典数据"""
        with open(self.dict_file, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
    
    def lookup(self, word: str) -> Optional[Dict]:
        """精确查询单词"""
        word = word.lower().strip()
        return self.dictionary.get(word)
    
    def fuzzy_search(self, word: str, n: int = 3) -> list:
        """模糊搜索,返回最相似的n个单词"""
        word = word.lower().strip()
        words = list(self.dictionary.keys())
        matches = difflib.get_close_matches(word, words, n=n, cutoff=0.6)
        return matches
    
    def add_word(self, word: str, data: Dict):
        """添加新单词到词典"""
        word = word.lower().strip()
        self.dictionary[word] = data
        self._save_dictionary(self.dictionary)
    
    def display_result(self, word: str):
        """格式化显示查询结果"""
        result = self.lookup(word)
        
        if not result:
            print(f"未找到单词 '{word}'")
            # 提供相似词建议
            suggestions = self.fuzzy_search(word)
            if suggestions:
                print(f"您是不是想查: {', '.join(suggestions)}")
            return
        
        print(f"\n=== {word.upper()} ===")
        print(f"音标: {result.get('phonetic', 'N/A')}")
        print("\n释义:")
        for i, meaning in enumerate(result.get('meanings', []), 1):
            print(f"  {i}. {meaning}")
        
        if result.get('examples'):
            print("\n例句:")
            for i, example in enumerate(result.get('examples', []), 1):
                print(f"  {i}. {example}")

# 使用示例
if __name__ == "__main__":
    # 初始化词典
    dict_tool = LocalDictionary()
    
    # 查询单词
    dict_tool.display_result("hello")
    
    # 模糊搜索
    print("\n模糊搜索 'pythn':", dict_tool.fuzzy_search("pythn"))
    
    # 添加新单词
    dict_tool.add_word("algorithm", {
        "phonetic": "/ˈælɡərɪðəm/",
        "meanings": ["n. 算法;计算程序"],
        "examples": ["The algorithm efficiently sorts the data."]
    })
    
    # 查询新添加的单词
    dict_tool.display_result("algorithm")

如果要连接在线API,这里是一个使用有道词典API的补充:

import requests
import hashlib
import time
import json

class OnlineDictionary:
    def __init__(self, app_key: str, app_secret: str):
        self.base_url = "https://openapi.youdao.com/api"
        self.app_key = app_key
        self.app_secret = app_secret
    
    def query(self, word: str) -> Dict:
        """查询在线词典"""
        salt = str(int(time.time()))
        sign_str = self.app_key + word + salt + self.app_secret
        sign = hashlib.md5(sign_str.encode()).hexdigest()
        
        params = {
            'q': word,
            'from': 'en',
            'to': 'zh-CHS',
            'appKey': self.app_key,
            'salt': salt,
            'sign': sign
        }
        
        try:
            response = requests.get(self.base_url, params=params)
            return response.json()
        except Exception as e:
            return {"error": str(e)}

# 混合使用本地和在线词典
class HybridDictionary:
    def __init__(self, local_file: str = "dictionary.json"):
        self.local = LocalDictionary(local_file)
        # 在线词典需要申请API密钥
        # self.online = OnlineDictionary("your_app_key", "your_app_secret")
    
    def smart_lookup(self, word: str):
        """智能查询:先查本地,没有则查在线"""
        # 本地查询
        result = self.local.lookup(word)
        if result:
            return {"source": "local", "data": result}
        
        # 在线查询(需要配置API)
        # online_result = self.online.query(word)
        # if online_result and 'translation' in online_result:
        #     # 缓存到本地
        #     self.local.add_word(word, self._parse_online_result(online_result))
        #     return {"source": "online", "data": online_result}
        
        return None

核心要点

  1. 本地词典用json存储,快速但数据有限
  2. 在线API(有道、金山等)数据全但需要网络和密钥
  3. 模糊搜索用difflib实现拼写容错
  4. 可以设计为混合模式:先查本地缓存,没有再查在线

建议:先实现本地版本,再考虑接入在线API。

这个不是非常简单, 直接跳转到相关英语词典的网站啊, 大部分都有手机版适配的.
跟墨墨没有关系, 也与 Python 无关.

#2 就写一个查询语句么,遇到没有的词怎么处理,另外可不可以用 PY 读取无手机适配的网站再改成可以适配的输出呢

换个问法,如何用 python 写一个查询窗口,也调用词典网站的释义并且适配窗口大小和排版

http://dictionary.cambridge.org/dictionary/english/grammar
自己用 chrome 切换到手机模式看, 适配是网站自己做的。

回到顶部