Module:PageSummary
武外梗百科 爱国好学自强图新的百科全书
更多操作
此模块的文档可以在Module:PageSummary/doc创建
local p = {}
-- 高性能清理函数
local function smartClean(text)
if not text then return "" end
-- 1. 预处理:去掉 HTML 注释、脚注、数学公式等标签块
text = mw.ustring.gsub(text, "<!%-%-.-%-%->", "")
text = mw.ustring.gsub(text, "<ref[^>]*>.-</ref>", "")
text = mw.ustring.gsub(text, "<ref[^>]-/>", "")
text = mw.ustring.gsub(text, "<math[^>]*>.-</math>", "")
-- 2. 去除表格 (MediaWiki 表格以 {| 开始,|} 结束)
-- 使用非贪婪匹配,重复执行以处理多个表格
text = mw.ustring.gsub(text, "{|[^{}]*|}", "") -- 先处理最内层不含嵌套的
text = mw.ustring.gsub(text, "{|.-|}", "") -- 扩展清理
-- 3. 递归剥离模板 {{...}}
-- 性能优化:限制循环次数,防止死循环
local prev, count = "", 0
repeat
prev = text
text = mw.ustring.gsub(text, "{{[^{}]-}}", "")
count = count + 1
until text == prev or count > 10
-- 4. 剥离图片、分类等 [[File:xxx]]
-- 逻辑:匹配所有中括号,如果是媒体文件则删掉,如果是普通链接则保留文字
text = mw.ustring.gsub(text, "%[%[([^%[%]]-)%]%]", function(inner)
local l_inner = mw.ustring.lower(inner)
if l_inner:match("^file:") or l_inner:match("^image:") or
l_inner:match("^category:") or l_inner:match("^文件:") or
l_inner:match("^图像:") or l_inner:match("^分类:") then
return "" -- 丢弃附件
end
-- 保留链接文字:[[A|B]] -> B, [[A]] -> A
local parts = mw.text.split(inner, "|")
return parts[#parts]
end)
-- 5. 清理剩余的格式字符
text = mw.ustring.gsub(text, "''+", "") -- 去掉粗斜体
text = mw.ustring.gsub(text, "==+.-==+", "") -- 去掉标题
text = mw.ustring.gsub(text, "\n%s*[*#:]+", " ") -- 列表转空格
text = mw.ustring.gsub(text, "\n+", " ") -- 换行转空格
text = mw.ustring.gsub(text, "%s+", " ") -- 压缩多余空格
return mw.text.trim(text)
end
function p.getSummaryAndImage(frame)
local pageName = frame.args[1] or ""
local title = mw.title.new(pageName)
if not title or not title.exists then return "" end
-- 性能优化:只读取前 2000 个字符进行解析,而不是全篇,防止超大页面卡死
local content = mw.ustring.sub(title:getContent() or "", 1, 2000)
-- 1. 提取第一张图(直接在原文找,不干扰摘要)
local firstImage = mw.ustring.match(content, "%[%[%s*[Ff]ile%s*:([^|%]%s]+)") or
mw.ustring.match(content, "%[%[%s*文件%s*:([^|%]%s]+)") or
mw.ustring.match(content, "%[%[%s*[Ii]mage%s*:([^|%]%s]+)")
-- 2. 提取摘要
local cleanText = smartClean(content)
local targetLen = 140
local summary = mw.ustring.sub(cleanText, 1, targetLen)
if mw.ustring.len(cleanText) > targetLen then
summary = summary .. "..."
end
-- 3. 渲染 UI
local container = mw.html.create('div'):css({
['margin-bottom'] = '20px',
['padding'] = '15px',
['border'] = '1px solid #e2e2e2',
['border-radius'] = '8px',
['background-color'] = '#fff',
['box-shadow'] = '0 2px 5px rgba(0,0,0,0.05)',
['display'] = 'flow-root'
})
-- 标题
container:tag('div')
:css({['font-size'] = '1.2em', ['font-weight'] = 'bold', ['margin-bottom'] = '8px', ['color'] = '#000'})
:wikitext('[[' .. pageName .. ']]')
-- 正文容器
local body = container:tag('div'):css({['font-size'] = '14px', ['line-height'] = '1.6', ['color'] = '#444'})
-- 图片右浮动
if firstImage then
body:wikitext('[[File:' .. firstImage .. '|100px|right|link=' .. pageName .. ']]')
end
body:wikitext(summary)
return tostring(container)
end
return p