Compare commits

..

1 Commits

Author SHA1 Message Date
李臻镪 2b74602bd8 LiZhenqiang's vocabulary.py 2025-07-01 16:05:02 +08:00
6 changed files with 170 additions and 7 deletions

View File

@ -18,7 +18,7 @@ picked from articles selected for him to read according his vocabulary level. E
`python3 main.py`
Make sure you have put the SQLite database file in the path `app/db` (see below).
Make sure you have put the SQLite database file in the path `app/static` (see below).
## Run it as a Docker container
@ -214,5 +214,5 @@ Bug report: http://118.25.96.118/bugzilla/show_bug.cgi?id=215
Bug report: http://118.25.96.118/bugzilla/show_bug.cgi?id=489
*Last modified on 2026-03-12*
*Last modified on 2023-01-30*

View File

@ -106,7 +106,7 @@ def get_today_article(user_word_list, visited_articles):
text_level = text_difficulty_level(d['text'], d3)
result_of_generate_article = "found"
today_article = {}
today_article = None
if d:
oxford_words = load_oxford_words(oxford_words_path)
oxford_word_count, total_words = count_oxford_words(d['text'],oxford_words)

View File

@ -144,8 +144,8 @@ if __name__ == '__main__':
运行程序
'''
# app.secret_key = os.urandom(16)
app.run(debug=True, port=5000)
# app.run(debug=True)
# app.run(debug=False, port='6000')
app.run(debug=True)
# app.run(debug=True, port='6000')
# app.run(host='0.0.0.0', debug=True, port='6000')
# print(mod5('123'))

View File

@ -31,7 +31,7 @@
<p><a href="/login">登录</a> <a href="/signup">注册</a> <a href="/static/usr/instructions.html">使用说明</a></p >
<p><b> {{ random_ads }}。 <a href="/signup">试试</a>吧!</b></p>
{% endif %}
<div class="alert alert-success" role="alert">共有文章 <span class="badge bg-success"> {{ number_of_essays }} </span> 篇,Oxford 5000 单词占比 <span class="badge bg-success"> {{ (ratio * 100) | int }}% </span> </div>
<div class="alert alert-success" role="alert">共有文章 <span class="badge bg-success"> {{ number_of_essays }} </span> 篇,覆盖 <span class="badge bg-success"> {{ (ratio * 100) | int }}% </span> 的 Oxford5000 单词</div>
<p>粘贴1篇文章 (English only)</p>
<form method="post" action="/">
<textarea name="content" id="article" rows="10" cols="120"></textarea><br/>

View File

@ -87,7 +87,7 @@
<div id="text-content">
<div id="found">
<div class="alert alert-success" role="alert">According to your word list, your level is <span class="text-decoration-underline" id="user_level">{{ today_article["user_level"] }}</span> and we have chosen an article with a difficulty level of <span class="text-decoration-underline" id="text_level">{{ today_article["text_level"] }}</span> for you. <span class="text-decoration-underline" id="ratio">{{ (today_article["ratio"] * 100) | int }}%</span> of the words in this article are in Oxford Word 5000.</div>
<div class="alert alert-success" role="alert">According to your word list, your level is <span class="text-decoration-underline" id="user_level">{{ today_article["user_level"] }}</span> and we have chosen an article with a difficulty level of <span class="text-decoration-underline" id="text_level">{{ today_article["text_level"] }}</span> for you. The Oxford word coverage is <span class="text-decoration-underline" id="ratio">{{ (today_article["ratio"] * 100) | int }}%.</span></div>
<p class="text-muted" id="date">Article added on: {{ today_article["date"] }}</p><br/>
<button onclick="saveArticle()" >标记文章</button>

163
app/vocabulary.py Normal file
View File

@ -0,0 +1,163 @@
import json
import os
from datetime import datetime
class VocabularyManager:
def __init__(self, data_file="vocabulary_data.json"):
"""
初始化词汇管理器
:param data_file: 词汇数据存储文件
"""
self.data_file = data_file
self.vocabulary = {}
self._load_data()
def _load_data(self):
"""从文件加载词汇数据"""
if os.path.exists(self.data_file):
try:
with open(self.data_file, 'r', encoding='utf-8') as f:
self.vocabulary = json.load(f)
except (json.JSONDecodeError, FileNotFoundError):
self.vocabulary = {}
def _save_data(self):
"""保存词汇数据到文件"""
with open(self.data_file, 'w', encoding='utf-8') as f:
json.dump(self.vocabulary, f, ensure_ascii=False, indent=2)
def add_word(self, word, definition, example=None, tags=None):
"""
添加新单词
:param word: 单词
:param definition: 释义
:param example: 例句可选
:param tags: 标签列表可选
:return: 添加结果消息
"""
if word.lower() in self.vocabulary:
return f"'{word}' already exists in vocabulary"
word_data = {
'definition': definition,
'example': example,
'tags': tags if tags else [],
'date_added': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
'review_count': 0,
'last_reviewed': None
}
self.vocabulary[word.lower()] = word_data
self._save_data()
return f"'{word}' added successfully"
def get_word(self, word):
"""
获取单词详情
:param word: 要查询的单词
:return: 单词数据字典不存在则返回None
"""
return self.vocabulary.get(word.lower())
def update_word(self, word, definition=None, example=None, tags=None):
"""
更新单词信息
:param word: 要更新的单词
:param definition: 新释义可选
:param example: 新例句可选
:param tags: 新标签列表可选
:return: 更新结果消息
"""
word_key = word.lower()
if word_key not in self.vocabulary:
return f"'{word}' not found in vocabulary"
if definition:
self.vocabulary[word_key]['definition'] = definition
if example is not None: # 允许空字符串
self.vocabulary[word_key]['example'] = example
if tags is not None: # 允许空列表
self.vocabulary[word_key]['tags'] = tags
self._save_data()
return f"'{word}' updated successfully"
def delete_word(self, word):
"""
删除单词
:param word: 要删除的单词
:return: 删除结果消息
"""
word_key = word.lower()
if word_key in self.vocabulary:
del self.vocabulary[word_key]
self._save_data()
return f"'{word}' deleted successfully"
return f"'{word}' not found in vocabulary"
def list_all_words(self):
"""
获取所有单词列表
:return: 按添加时间排序的单词列表
"""
return sorted(
self.vocabulary.keys(),
key=lambda w: self.vocabulary[w]['date_added'],
reverse=True
)
def record_review(self, word):
"""
记录单词复习
:param word: 复习的单词
:return: 复习记录结果
"""
word_key = word.lower()
if word_key in self.vocabulary:
self.vocabulary[word_key]['review_count'] += 1
self.vocabulary[word_key]['last_reviewed'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self._save_data()
return f"Review recorded for '{word}'"
return f"'{word}' not found in vocabulary"
def search_words(self, keyword):
"""
搜索包含关键字的单词
:param keyword: 搜索关键字
:return: 匹配的单词列表
"""
keyword = keyword.lower()
return [
word for word, data in self.vocabulary.items()
if keyword in word or
keyword in data['definition'].lower() or
(data['example'] and keyword in data['example'].lower())
]
# 示例用法
if __name__ == "__main__":
vm = VocabularyManager()
# 添加单词
print(vm.add_word("ephemeral", "短暂的,瞬息的",
"Beauty is ephemeral, lasting only a few moments.",
["adjective", "literary"]))
# 获取单词详情
print("\nWord details:")
print(vm.get_word("ephemeral"))
# 更新单词
print(vm.update_word("ephemeral", tags=["adjective", "poetic"]))
# 记录复习
print(vm.record_review("ephemeral"))
# 列出所有单词
print("\nAll words:")
print(vm.list_all_words())
# 搜索单词
print("\nSearch results:")
print(vm.search_words("brief"))