![使用 LuaLaTeX 创建单独的文件](https://linux22.com/image/437312/%E4%BD%BF%E7%94%A8%20LuaLaTeX%20%E5%88%9B%E5%BB%BA%E5%8D%95%E7%8B%AC%E7%9A%84%E6%96%87%E4%BB%B6.png)
我的输入 LaTeX 文件名是Article05.tex
。我想查找文本<stepn number>(.-)</stepn number>
并将文本存储为单独的文件,例如名称是Article05-step.tex
。如何实现这一点LuaLaTeX
?
我的 MWE 是:
\documentclass{article}
\usepackage{luacode}
\begin{luacode*}
xml = require('luaxml-mod-xml')
handler = require('luaxml-mod-handler')
\end{luacode*}
\begin{document}
\begin{luacode*}
sample = [[
<?xml version="1.0" encoding="utf-8"?>
<art>
<title>Scattering of flexural waves an electric current</title>
<para>Smart testing structures are components <step1>Reduce acoustic noise.</step1> used in engineering applications that are capable of sensing or reacting to their environment <step3>Change their mechanical properties.</step3> in a predictable and desired manner. In addition to <step2>Carrying mechanical loads</step2>, <!--may smart structures--> alleviate vibration, reduce acoustic noise, change their mechanical properties as required or monitor their own condition.</para>
</art>]]
treehandler = handler.simpleTreeHandler()
x = xml.xmlParser(treehandler)
x:parse(sample)
tex.sprint(treehandler.root["art"]["title"])
for _, element in ipairs(treehandler.root["art"]["para"]) do
--if element._attr["attr"] == "A2" then
--tex.print("\\\\")
--tex.sprint(element)
--end
end
\end{luacode*}
\end{document}
应该Article05-step.tex
是:
STEP1: Reduce acoustic noise.
STEP2: Change their mechanical properties.
答案1
尝试这个:
\documentclass{article}
\usepackage{luacode}
\begin{document}
\begin{luacode*}
local domobject = require "luaxml-domobject"
sample = [[
<?xml version="1.0" encoding="utf-8"?>
<art>
<title>Scattering of flexural waves an electric current</title>
<para>Smart testing structures are components <step1>Reduce acoustic noise.</step1> used in engineering applications that are capable of sensing or reacting to their environment <step2>Change their mechanical properties.</step2> in a predictable and desired manner. In addition to carrying mechanical loads, <!--may smart structures--> alleviate vibration, reduce acoustic noise, change their mechanical properties as required or monitor their own condition.</para>
</art>
]]
local f = io.open(tex.jobname .. "-step.tex", "w")
local dom = domobject.parse(sample)
local steps = {}
dom:traverse_elements(function(el)
-- detect if element is named stepN
local number = el:get_element_name():match("^step([0-9]+)")
if number then
steps[#steps+1] = {number = tonumber(number), text = el:get_text()}
-- f:write("STEP" .. number ..": " .. .. "\n")
end
end)
table.sort(steps, function(a, b) return a.number < b.number end)
for k,v in ipairs(steps) do
f:write("STEP" .. v.number ..": " .. v.text .. "\n")
end
f:close()
\end{luacode*}
\end{document}
它使用 LuaXML 的 DOM 对象。该dom:traverse_elements
函数循环遍历所有元素,检测元素名称是否以 开头step
,并将其文本内容保存到\jobname-step.tex
文件中。
结果如下:
STEP1: Reduce acoustic noise.
STEP2: Change their mechanical properties.