You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
DjangoBlog/plugins/reading_time/plugin.py

69 lines
3.0 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 导入数学运算模块,用于向上取整计算
import math
# 导入正则表达式模块用于处理HTML内容和文本分词
import re
# 导入Django博客插件基类当前插件需继承此类
from djangoblog.plugin_manage.base_plugin import BasePlugin
# 导入插件钩子管理模块,用于注册插件功能
from djangoblog.plugin_manage import hooks
# 导入文章内容钩子常量,指定插件作用的位置
from djangoblog.plugin_manage.hook_constants import ARTICLE_CONTENT_HOOK_NAME
class ReadingTimePlugin(BasePlugin):
# 插件名称,用于插件管理界面展示
PLUGIN_NAME = '阅读时间预测'
# 插件功能描述,说明核心作用
PLUGIN_DESCRIPTION = '估算文章阅读时间并显示在文章开头。'
# 插件版本号
PLUGIN_VERSION = '0.1.0'
# 插件作者信息
PLUGIN_AUTHOR = 'liangliangyy'
def register_hooks(self):
"""注册插件钩子,将处理方法绑定到文章内容钩子"""
# 当文章内容被渲染时触发add_reading_time方法
hooks.register(ARTICLE_CONTENT_HOOK_NAME, self.add_reading_time)
def add_reading_time(self, content, *args, **kwargs):
"""
计算文章阅读时间并添加到内容开头
参数:
content: 文章原始HTML内容
*args, **kwargs: 预留参数,用于接收额外信息
返回:
添加了阅读时间信息的HTML内容
"""
# 1. 清理内容使用正则移除所有HTML标签<...>格式),保留纯文本
clean_content = re.sub(r'<[^>]*>', '', content)
# 移除文本前后的空白字符(空格、换行等)
clean_content = clean_content.strip()
# 2. 计数单词/字符:
# 正则匹配规则:匹配单个中文字符([\u4e00-\u9fa5])或连续的非中文字符(视为英文单词,\w+
# 这样处理中英文混合的内容,兼顾两种语言的计数逻辑
words = re.findall(r'[\u4e00-\u9fa5]|\w+', clean_content)
# 统计匹配到的元素数量(中文按单个字算,英文按单词算)
word_count = len(words)
# 3. 计算阅读时间:
# 设定平均阅读速度为每分钟200字中英文通用的经验值
reading_speed = 200
# 总字数除以阅读速度,向上取整得到分钟数
reading_minutes = math.ceil(word_count / reading_speed)
# 处理边界情况如果计算结果小于1分钟强制显示为1分钟
if reading_minutes < 1:
reading_minutes = 1
# 4. 生成阅读时间的HTML片段
# 使用浅灰色文字,斜体样式,显示在段落中
reading_time_html = f'<p style="color: #888;"><em>预计阅读时间:{reading_minutes} 分钟</em></p>'
# 将阅读时间信息添加到文章内容开头并返回
return reading_time_html + content
# 实例化插件,使插件系统能够识别并加载
plugin = ReadingTimePlugin()