You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Lua编写自定义Pandoc HTML Reader解析<title>为Header对象?

用Pandoc Lua自定义Reader解析HTML的标签 <a class="header-anchor" href="#用pandoc-lua自定义reader解析html的标签" aria-hidden="true">#</a></h1> <p>完全可以通过Lua自定义Reader实现这个需求,以下是具体的实现方案:</p> <h2 id="编写自定义lua-reader脚本">编写自定义Lua Reader脚本 <a class="header-anchor" href="#编写自定义lua-reader脚本" aria-hidden="true">#</a></h2> <p>创建一个名为<code>title-reader.lua</code>的脚本,通过重载HTML Reader的标签处理逻辑来捕获<code><title></code>内容并转为Header对象:</p> <pre class="hljs"><code class="language-lua volc-pre-code">function Html.reader() local reader = pandoc.readers.html() local original_starttag = reader.starttag reader.starttag = function(tag, attrs, self) if tag == 'title' then -- 读取<title>标签内的文本内容 local title_content = self:read_text() -- 生成Level 1的Header对象 local title_header = pandoc.Header(1, pandoc.Str(title_content)) -- 将标题插入到文档内容的最开头 table.insert(self.contents, 1, title_header) return true else -- 其他标签沿用默认解析逻辑 return original_starttag(tag, attrs, self) end end return reader end </code></pre> <h2 id="执行命令">执行命令 <a class="header-anchor" href="#执行命令" aria-hidden="true">#</a></h2> <p>运行Pandoc时指定这个自定义Lua脚本即可:</p> <pre class="hljs"><code class="language-bash volc-pre-code">pandoc --lua-filter title-reader.lua input.html -t native </code></pre> <h2 id="效果说明">效果说明 <a class="header-anchor" href="#效果说明" aria-hidden="true">#</a></h2> <ul> <li>脚本会自动捕获HTML中的<code><title></code>文本,将其转为一级标题(Header 1)并放在文档内容的最前面</li> <li>文档中其他HTML标签的解析逻辑完全保留Pandoc默认行为,不会影响原有内容的处理</li> </ul> <p>内容的提问来源于stack exchange,提问作者freddie_ventura</p>
相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 00:59:58