模組:Conversion rule extractor
外观

![]() | 此模块已评为alpha版,可接受第三方输入,并可用于少量页面以检查是否存在问题,但需要受到检查。欢迎提供新功能或修改其输入输出机制的建议。 |
![]() | 此模块使用Lua语言: |
本模块用于提取指定页面的字词转换规则(包括手动规则和公共转换组规则),并根据需要筛选出能在特定目标页面或标题上匹配使用的规则,最终以不同格式输出。
子模块
- Module:Conversion_rule_extractor/Extractor – 用于提取规则
- Module:Conversion_rule_extractor/Matcher – 用于匹配规则
函数
getRules
获取指定来源页面的所有内容转换规则(手动+公共组),并筛选出能在目标页面内容中匹配到的规则。
调用方式: {{#invoke:Conversion_rule_extractor|getRules|from=来源页面|to=目标页面|flag=输出格式}}
参数:
- from 或匿名参数 1: (必须) 字符串,规则来源页面的标题。
- to: (可选) 字符串,用于匹配规则的目标页面标题。默认为调用模块的当前页面。
- flag: (可选) 字符串,指定输出规则的旗标。
- H (默认): 输出为
-{H|规则;}-
格式。 - raw: 直接输出规则文本,每条规则占一行。
- 其他值 (如 A, D): 输出为
-{值|规则;}-
格式。
- H (默认): 输出为
返回值: 字符串,格式化后的、能在目标页面匹配到的内容转换规则。如果来源页不存在或无匹配规则,返回空字符串。如果缺少 from 参数,返回错误提示信息。
getTitleRule
获取应用于指定来源页面标题的转换规则。
- 如果来源页面有显式的标题 (T) 规则,则使用该规则。
- 如果没有显式标题规则,则尝试将来源页面的所有内容规则与其标题文本进行匹配,使用匹配到的规则。
调用方式: {{#invoke:Conversion_rule_extractor|getTitleRule|from=来源页面|flag=输出格式|type=输出类型}}
参数:
- from 或匿名参数 1: (必须) 字符串,规则来源页面的标题。
- flag: (可选) 字符串,指定输出规则的旗标(当type不为context时生效)。
- H (默认): 输出为
-{H|规则;}-
格式。 - raw: 直接输出规则文本,每条规则占一行。
- 其他值: 输出为
-{值|规则;}-
格式。如果规则来源于内容规则匹配,即使指定flag='T',也会强制使用H。
- H (默认): 输出为
- type: (可选) 字符串,指定输出类型。
- context: (特殊模式) 如果存在显式T规则,输出为
-{T规则;}-
。如果不存在显式T规则,但有内容规则匹配标题,输出为-{H|匹配的内容规则;}-原始标题
。 - 其他值或省略: 按flag参数指定的格式输出规则本身。
- context: (特殊模式) 如果存在显式T规则,输出为
返回值: 字符串,格式化后的标题转换规则或带规则的标题文本。如果来源页不存在或无适用规则,返回空字符串。如果缺少from参数或来源页不存在,返回错误提示信息。
参见
- {{NoteTA-lite}}
local p = {}
local TPV = require('Module:Template parameter value')
local Arguments = require('Module:Arguments') -- 用于模板入口点
local mw_text = require('mw.text') -- 用于分割和裁剪
local mw_html = require('mw.html') -- 用于创建 HTML 元素 (可选,备用错误处理)
-- 以下模板的重定向检索于2025-05-03
local NOTE_TA_TEMPLATES = {
'NoteTA', 'TA', 'NoteAT', 'NoteTA/default', 'NOTETA', 'Note TA', 'Noteta', 'NoteTa', 'NoteTA/lua', '全文字词转换',
'NoteTA-lite', 'TA-lite', 'TAL', 'TAl'
}
local MAX_LOCAL_RULES = 30 -- 本地规则查找上限
local MAX_GROUP_RULES = 30 -- 公共转换组查找上限
--[[--------------------------< 辅助函数 - CGroup 处理 >--------------------------]]
-- 安全地加载 CGroup 模块数据 (同前)
local function loadCGroupData(groupName)
local moduleTitleStr = 'Module:CGroup/' .. groupName
local success, data
local titleObj = mw.title.new(moduleTitleStr)
if titleObj and titleObj.exists then
-- 使用 pcall 保护 loadData
success, data = pcall(mw.loadData, moduleTitleStr)
if success and type(data) == 'table' then -- 检查 loadData 是否成功且返回的是表
return data
else
-- 可选:记录加载失败或数据类型错误
mw.log('ConversionRuleExtractor: Failed to load or parse CGroup module: ' .. moduleTitleStr .. (success and ' (invalid data type)' or ' (load error)'))
return nil
end
end
return nil
end
-- 从加载的 CGroup 数据中提取规则 (同前)
local function extractRulesFromCGroupData(data)
local rules = {}
-- 添加检查 data.content 是否为 table
if data and data.content and type(data.content) == 'table' then
for _, item in ipairs(data.content) do
-- 确保 item 是 table 且包含有效的 rule 字符串
if type(item) == 'table' and item.type == 'item' and type(item.rule) == 'string' and item.rule ~= '' then
table.insert(rules, item.rule)
end
end
end
return rules
end
--[[--------------------------< 辅助函数 - 规则解析与过滤 >--------------------------]]
-- 从单个规则字符串中提取所有可能的源文本 (用于匹配) (同前)
local function extractSourceTerms(ruleString)
local sources = {}
local rulePart = ruleString
local arrowPos = string.find(rulePart, '=>', 1, true)
if arrowPos then
rulePart = mw_text.trim(string.sub(rulePart, 1, arrowPos - 1))
end
for segment in mw_text.gsplit(rulePart, ';') do
segment = mw_text.trim(segment)
if segment ~= '' then
local term
local colonPos = string.find(segment, ':', 1, true)
if colonPos then
term = mw_text.trim(string.sub(segment, colonPos + 1))
else
term = segment
end
if term ~= '' then
-- 进一步去除可能的 HTML 标签,虽然不太常见但在规则中可能存在
term = mw_text.strip(term)
if term ~= '' then
table.insert(sources, term)
end
end
end
end
return sources
end
-- 过滤 CGroup 规则列表,只保留至少一个源文本在目标文本中出现的规则 (同前)
local function filterGroupRulesByText(groupRules, textToMatch)
if not textToMatch or textToMatch == '' or not groupRules or #groupRules == 0 then
return {}
end
local filteredRules = {}
-- 预处理 textToMatch,去除 HTML 标记以提高匹配准确性
local cleanTextToMatch = mw_text.strip(textToMatch)
if cleanTextToMatch == '' then return {} end -- 如果去除标记后为空,则无法匹配
for _, ruleString in ipairs(groupRules) do
local sourceTerms = extractSourceTerms(ruleString)
local matched = false
for _, term in ipairs(sourceTerms) do
-- 使用不区分大小写的查找可能更鲁棒,但暂时保持区分大小写
-- 注意:mw.ustring.find 可能更适合处理 Unicode,但 string.find 对 UTF-8 通常也有效
if string.find(cleanTextToMatch, term, 1, true) then
matched = true
break
end
end
if matched then
table.insert(filteredRules, ruleString)
end
end
return filteredRules
end
--[[--------------------------< 辅助函数 - 格式化输出 >--------------------------]]
-- 将规则列表格式化为最终输出字符串 (同前)
local function formatRules(rules, flag)
if not rules or #rules == 0 then
return ''
end
flag = (type(flag) == 'string' and flag ~= '') and flag or 'H' -- 默认 flag 为 'H'
if flag == 'raw' then
return table.concat(rules, "\n")
else
local wrapped_rules = {}
for _, rule in ipairs(rules) do
table.insert(wrapped_rules, "-{" .. flag .. "|" .. rule .. "}-")
end
return table.concat(wrapped_rules, "")
end
end
--[[--------------------------< 核心获取函数 >--------------------------]]
-- 内部函数,获取原始规则数据 (同前, 确保 ['local'] 使用正确)
function p._internal_fetchAllRules(pageTitleString)
local allRules = {
title = nil,
['local'] = {},
groups = {}
}
local foundTemplate = false
local titleObj = mw.title.new(pageTitleString)
if not titleObj then
mw.log('ConversionRuleExtractor: Invalid page title provided for fetching rules: ' .. pageTitleString)
return nil
end
-- 1. 获取标题规则 (T)
local success_t, titleRule = TPV.getParameter(pageTitleString, NOTE_TA_TEMPLATES, 'T')
if success_t and titleRule and titleRule ~= '' then
allRules.title = titleRule
foundTemplate = true
end
-- 2. 获取本地规则 (1..MAX_LOCAL_RULES)
for i = 1, MAX_LOCAL_RULES do
local paramName = tostring(i)
local success_l, localRule = TPV.getParameter(pageTitleString, NOTE_TA_TEMPLATES, paramName)
if success_l and localRule and localRule ~= '' then
table.insert(allRules['local'], localRule)
foundTemplate = true
elseif not success_l then
if localRule == "No valid template found" and not foundTemplate then
if i == 1 then return nil end -- 第一次查询就失败且无T,则无模板
end
-- 假设本地规则连续,提前退出
break
end
end
-- 3. 获取组规则 (G1..MAX_GROUP_RULES)
for i = 1, MAX_GROUP_RULES do
local paramName = 'G' .. i
local success_g, groupName = TPV.getParameter(pageTitleString, NOTE_TA_TEMPLATES, paramName)
if success_g and groupName and groupName ~= '' then
foundTemplate = true
local groupData = loadCGroupData(groupName)
if groupData then
local rulesFromGroup = extractRulesFromCGroupData(groupData)
if #rulesFromGroup > 0 then
table.insert(allRules.groups, { name = groupName, rules = rulesFromGroup })
end
end
elseif not success_g then
if groupName == "No valid template found" and not foundTemplate then
if i == 1 then return nil end -- 第一次查询就失败且无T和local,则无模板
end
-- 假设 G 规则连续,提前退出
break
end
end
if foundTemplate then
return allRules
else
return nil
end
end
--[[--------------------------< 公开函数 >--------------------------]]
-- 获取全文转换规则(本地 + 所有组规则)并格式化输出 (同前)
function p.getFullTextRules(pageTitle, flag)
local pageTitleString
if type(pageTitle) == 'string' then -- 使用全局 type()
pageTitleString = pageTitle
elseif type(pageTitle) == 'userdata' and getmetatable(pageTitle) == 'mw.title' then -- 使用全局 type()
pageTitleString = pageTitle.fullText
else
return ''
end
local allRulesData = p._internal_fetchAllRules(pageTitleString)
if not allRulesData then
return ''
end
local combinedRules = {}
if allRulesData['local'] then
for _, rule in ipairs(allRulesData['local']) do table.insert(combinedRules, rule) end
end
if allRulesData.groups then
for _, groupInfo in ipairs(allRulesData.groups) do
if groupInfo.rules then
for _, rule in ipairs(groupInfo.rules) do table.insert(combinedRules, rule) end
end
end
end
return formatRules(combinedRules, flag)
end
--[[
-- @description 获取标题转换规则(T 或 本地 + 匹配的组规则)并格式化或应用
-- @param pageTitle string|mw.title 页面标题
-- @param flag string|nil 输出格式标志 ('H', 'raw', 'A', etc.)
-- @param outputType string|nil 'context' 表示应用规则,否则忽略 (修正:重命名参数)
-- @param frame table The frame object (必需当 outputType='context')
-- @return string 格式化/应用后的字符串,或空字符串
--]]
function p.getTitleRules(pageTitle, flag, outputType, frame) -- 修正:重命名参数 type 为 outputType
local pageTitleString
local titleObj
-- 使用全局 type() 检查 pageTitle 类型
if type(pageTitle) == 'string' then
pageTitleString = pageTitle
-- pcall 保护 title.new
local success_title
success_title, titleObj = pcall(mw.title.new, pageTitleString)
if not success_title or not titleObj then
mw.log('ConversionRuleExtractor: Failed to create title object for: ' .. pageTitleString)
return '' -- 创建标题对象失败
end
elseif type(pageTitle) == 'userdata' and getmetatable(pageTitle) == 'mw.title' then
pageTitleString = pageTitle.fullText
titleObj = pageTitle
else
return '' -- 无效输入
end
-- 此时 titleObj 应该有效
local titleText = titleObj:getText() -- 获取用于匹配的原始标题文本
local allRulesData = p._internal_fetchAllRules(pageTitleString)
if not allRulesData then
-- 如果是 context 模式,返回原始标题;否则返回空字符串
return (outputType == 'context') and titleText or '' -- 修正:使用 outputType
end
-- 处理 outputType = 'context'
if outputType == 'context' then -- 修正:使用 outputType
if not frame then
-- 返回错误信息,而不是直接报错
return mw_html.create('span')
:addClass('error')
:wikitext("错误:type='context' 需要 frame 对象。"):allToString()
end
-- 如果存在 T 规则,优先使用 T 规则
if allRulesData.title and allRulesData.title ~= '' then
local rule_wikitext = "-{T|" .. allRulesData.title .. "}-"
-- T 规则本身就是结果,不需要附加原标题
-- 使用 pcall 保护 preprocess
local success_preprocess, result = pcall(frame.preprocess, frame, rule_wikitext)
if success_preprocess then
return result
else
mw.log('ConversionRuleExtractor: frame:preprocess failed for T rule on page ' .. pageTitleString .. ': ' .. tostring(result))
return mw_html.create('span')
:addClass('error')
:wikitext("处理T规则时出错。"):allToString()
end
else
-- 没有 T 规则,组合本地规则和匹配的组规则
local applicableRules = {}
if allRulesData['local'] then
for _, rule in ipairs(allRulesData['local']) do table.insert(applicableRules, rule) end
end
local allGroupRules = {}
if allRulesData.groups then
for _, groupInfo in ipairs(allRulesData.groups) do
if groupInfo.rules then
for _, rule in ipairs(groupInfo.rules) do table.insert(allGroupRules, rule) end
end
end
end
local filteredGroupRules = filterGroupRulesByText(allGroupRules, titleText)
for _, rule in ipairs(filteredGroupRules) do table.insert(applicableRules, rule) end
if #applicableRules == 0 then
return titleText -- 没有适用的规则,返回原始标题
else
-- 将所有适用的规则格式化为 H 规则块
local rules_wikitext = formatRules(applicableRules, 'H')
-- 将规则应用到原始标题文本前
-- 使用 pcall 保护 preprocess
local success_preprocess, result = pcall(frame.preprocess, frame, rules_wikitext .. titleText)
if success_preprocess then
return result
else
mw.log('ConversionRuleExtractor: frame:preprocess failed for H rules on page ' .. pageTitleString .. ': ' .. tostring(result))
return mw_html.create('span')
:addClass('error')
:wikitext("应用H规则时出错。"):allToString()
end
end
end
else
-- 处理格式化输出 (非 context)
local combinedRules = {}
if allRulesData.title and allRulesData.title ~= '' then
table.insert(combinedRules, allRulesData.title)
end
if allRulesData['local'] then
for _, rule in ipairs(allRulesData['local']) do table.insert(combinedRules, rule) end
end
local allGroupRules = {}
if allRulesData.groups then
for _, groupInfo in ipairs(allRulesData.groups) do
if groupInfo.rules then
for _, rule in ipairs(groupInfo.rules) do table.insert(allGroupRules, rule) end
end
end
end
local filteredGroupRules = filterGroupRulesByText(allGroupRules, titleText)
for _, rule in ipairs(filteredGroupRules) do table.insert(combinedRules, rule) end
return formatRules(combinedRules, flag)
end
end
--[[--------------------------< 模板入口点 >--------------------------]]
-- {{#invoke:ConversionRuleExtractor|getFullText|页面标题|flag=标志}}
function p.getFullText(frame)
local args = Arguments.getArgs(frame)
local page = args[1] or args.page
local flag = args.flag or 'H' -- flag 默认为 H
if not page or page == '' then
return mw_html.create('span')
:addClass('error')
:wikitext("错误:必须提供页面标题。"):allToString()
end
local result = p.getFullTextRules(page, flag)
return result
end
-- {{#invoke:ConversionRuleExtractor|getTitle|页面标题|flag=标志|type=context}}
function p.getTitle(frame)
local args = Arguments.getArgs(frame)
local page = args[1] or args.page
local flag = args.flag -- 不设默认值,由 getTitleRules 处理
local outputType = args.type -- 修正:读取参数到 outputType
if not page or page == '' then
return mw_html.create('span')
:addClass('error')
:wikitext("错误:必须提供页面标题。"):allToString()
end
-- 修正:传递 outputType 参数
local result = p.getTitleRules(page, flag, outputType, frame)
return result
end
return p