如何在Julia语言中使用dictionary和DataFrame与Mustache.jl呈现?
我使用模板生成TeX文件,并使用Mustache渲染该模板 首先,我有数据帧中的数据:如何在Julia语言中使用dictionary和DataFrame与Mustache.jl呈现?,julia,mustache,Julia,Mustache,我使用模板生成TeX文件,并使用Mustache渲染该模板 首先,我有数据帧中的数据: Row │ label │ score │ max │ │ │ Int64 │ Int64 │ Int64 │ ├─────┼───────┼───────┼───────┤ │ 1 │ 1 │ 2 │ 4 │ │ 2 │ 2 │ 3 │ 5 │ │ 3 │ 3 │ 4 │ 6 │ │ 4 │ 4 │
Row │ label │ score │ max │
│ │ Int64 │ Int64 │ Int64 │
├─────┼───────┼───────┼───────┤
│ 1 │ 1 │ 2 │ 4 │
│ 2 │ 2 │ 3 │ 5 │
│ 3 │ 3 │ 4 │ 6 │
│ 4 │ 4 │ 5 │ 7 │
还有一本字典:
student = Dict( "name" => "John", "surname" => "Smith");
我希望呈现一个模板,以便在模板中替换字典变量和数据帧变量。可以使用字典或数据帧,但不能同时使用两者
例如,渲染仅在具有如下所示模板“tmpl”的数据帧上工作:
tmpl = """
Your marks are:
\\begin{itemize}
{{#:D}}
\\item Mark for question {{:label}} is {{:score}} out of {{:max}}
{{/:D}}
"""
rendered_marks = render(tmpl, D=df );
但是,当我从“student”字典中添加变量(如:name或:姓氏)时,会收到错误消息:
marks_tmpl = """
Hello \\textbf{ {{:name}}, {{:surname}} }
Your marks are:
\\begin{itemize}
{{#:D}}
\\item Mark for question {{:label}} is {{:score}} out of {{:max}}
{{/:D}}
\\end{itemize}
\\end{document}
"""
rendered_marks = render(tmpl, student, D=df );
正确的方法是什么?不允许混合
Dict
和关键字参数。最简单的方法是将数据帧添加到字典中
首先,创建数据帧
:
df = DataFrame(label=1:4, score=2:5, max=4:7)
4×3 DataFrame
│ Row │ label │ score │ max │
│ │ Int64 │ Int64 │ Int64 │
├─────┼───────┼───────┼───────┤
│ 1 │ 1 │ 2 │ 4 │
│ 2 │ 2 │ 3 │ 5 │
│ 3 │ 3 │ 4 │ 6 │
│ 4 │ 4 │ 5 │ 7 │
接下来,参考字典中的数据帧
,以进行Mustache.jl渲染:
student = Dict( "name" => "John", "surname" => "Smith", "df" => df);
marks_tmpl = """
Hello \\textbf{ {{name}}, {{surname}} }
Your marks are:
\\begin{itemize}
{{#df}}
\\item Mark for question {{:label}} is {{:score}} out of {{:max}}
{{/df}}
\\end{itemize}
"""
这样,字典和数据帧
变量都被呈现:
julia> println(render(marks_tmpl, student))
Hello \textbf{ John, Smith }
Your marks are:
\begin{itemize}
\item Mark for question 1 is 2 out of 4
\item Mark for question 2 is 3 out of 5
\item Mark for question 3 is 4 out of 6
\item Mark for question 4 is 5 out of 7
\end{itemize}
我猜这就是您想要的?要补充答案,您还可以使用iterable访问字典中的键,或者使用命名为tuple的选项:
tmpl = """
Hello {{#:E}}\\textbf{ {{:name}}, {{:surname}} }{{/:E}}
Your marks are:
\\begin{itemize}
{{#:D}}
\\item Mark for question {{:label}} is {{:score}} out of {{:max}}
{{/:D}}
\\end{itemize}
\\end{document}
"""
using Mustache
using DataFrames
student = Dict( "name" => "John", "surname" => "Smith");
D = DataFrame(label=[1,2], score=[80,90])
Mustache.render(tmpl, E=(name="John",surname="Doe"),D=D, max=100)
因此,字典似乎可以指向外部数据帧,Mustache.jl将解析该数据帧。这有助于将Mustache.jl渲染的所有信息保存在一个整洁的地方。是的。另一种方法是,例如,将
数据框
、姓名和姓氏作为三个关键字参数传递。确定。因此,它是一个参数列表(包括变量和数据帧)或一个单独的字典对象,其中包含这些参数作为key=>value对。