这是我采用的解决方案。感谢所有的帮助。
解决方案的主要步骤是通过内核格式化命令:-
FullForm[ToBoxes[
Defer[Plot[{Exp[x],
Interpolation[Table[{k/5, Exp[(k - 1/2)/5]}, {k, 0, 5}],
InterpolationOrder -> 0][x]}, {x, 0, 1},
Filling -> {1 -> {{2}, {Yellow, Orange}}},
PlotLabel ->
Style["Formatting", Blue, FontFamily -> "Courier"]]]]]
然后封装格式化的数据创建一个笔记本:-
Notebook[{Cell[BoxData[
... ( inserted box-formatted output ) ...
], "Input"]
},
WindowSize->{615, 750},
WindowMargins->{{328, Automatic}, {Automatic, 76}},
StyleDefinitions->"Default.nb"
]
这将写入一个后缀为“.nb”的文件。一切都很好,花花公子。
这种方法适用于多语句代码块,但包含一些额外的处理来格式化 Function[expression, options] 形式的单个函数调用,以便在每个选项之前添加换行符。这是用于产生两种类型输出的 C# 代码:-
public static class MathematicaHelpers
{
public static string CreateNotebook(string mathCommand, string fileLocation, MathKernel kernel, bool addNewLines)
{
if (addNewLines) {
mathCommand = string.Format("{0}{1}{2}", "Module[{boxoutput,b2},boxoutput=FullForm[ToBoxes[Defer[", mathCommand, "]]];b2=boxoutput[[1,1,3,1]];boxoutput[[1,1,3,1]]=Join[Flatten[Riffle[Partition[b2,2],\"\\[IndentingNewLine]\"],1],{\"\\[IndentingNewLine]\",Last[b2]}];boxoutput]");
} else {
mathCommand = string.Format("{0}{1}{2}", "FullForm[ToBoxes[Defer[", mathCommand, "]]]");
}
fileLocation = Path.ChangeExtension(fileLocation, ".nb");
mathCommand = ComputeMathCommand(mathCommand, kernel);
mathCommand = string.Format("{0}{1}{2}", "Notebook[{Cell[BoxData[", mathCommand,
"], \"Input\"]},WindowSize->{615, 750}, WindowMargins->{{328, Automatic}, {Automatic, 76}},StyleDefinitions->\"Default.nb\"]");
File.WriteAllText(fileLocation, mathCommand);
return fileLocation;
}
private static string ComputeMathCommand(string command, MathKernel kernel)
{
kernel.Compute(command);
return kernel.Result.ToString();
}
}