请求编写Pandoc Lua过滤器:替换中文文献引用的et al.为‘等’
Pandoc Lua过滤器实现中英文引用格式区分
实现思路
针对中文文献引用中错误出现的“et al.”,我们通过Lua过滤器遍历Pandoc生成的AST,识别中文文献的引用节点,将其中的“et al.”替换为中文的“等”。核心逻辑是:
- 维护中文文献的citekey列表,用于区分中英文引用
- 遍历Cite元素,对中文引用的内容进行精准文本替换
过滤器代码
将以下代码保存为chinese-cite-filter.lua:
function Cite(cite) -- 配置中文文献的citekey,按需添加更多条目 local chinese_citekeys = { ["luohongyun2018"] = true } -- 判断当前引用是否属于中文文献 local is_chinese_cite = false for _, cit in ipairs(cite.citations) do if chinese_citekeys[cit.id] then is_chinese_cite = true break end end if not is_chinese_cite then return nil -- 非中文引用,直接返回原内容 end -- 替换"et al."为"等" local new_content = {} local idx = 1 while idx <= #cite.content do -- 匹配连续的"et" + 空格 + "al."序列 if idx <= #cite.content - 2 and cite.content[idx].t == "Str" and cite.content[idx].text == "et" and cite.content[idx+1].t == "Space" and cite.content[idx+2].t == "Str" and cite.content[idx+2].text == "al." then table.insert(new_content, pandoc.Str("等")) -- 也可写pandoc.Str("\31561"),效果完全一致 idx = idx + 3 else table.insert(new_content, cite.content[idx]) idx = idx + 1 end end return pandoc.Cite(cite.citations, new_content) end
使用方法
- 修改代码中的
chinese_citekeys表,将所有中文文献的citekey添加进去(比如新增["wang2020"] = true) - 执行Pandoc命令时加载该过滤器:
pandoc -C --lua-filter=chinese-cite-filter.lua test.md -o output.md
(可根据需求替换output.md为其他格式,如output.pdf或output.docx)
说明
- 代码中直接使用“等”而非
\31561是因为现代Lua支持UTF-8编码,两种写法效果完全一致 - 过滤器会精准匹配“et”+空格+“al.”的序列,避免误替换其他文本中的相似内容
内容的提问来源于stack exchange,提问作者TomBen
相关产品推荐
相关产品推荐

