jxy*_*jxy 26 wolfram-mathematica
我不知道为什么维基百科将Mathematica列为printf的编程语言.我在Mathematica中找不到相应的东西.
我的具体任务是处理带有填充数字的数据文件列表,我曾经在bash中使用
fn=$(printf "filename_%05d" $n)
Run Code Online (Sandbox Code Playgroud)
我在Mathematica中找到的最接近的函数是PaddedForm.经过一些反复试验,我得到了它
"filename_" <> PaddedForm[ Round@#, 4, NumberPadding -> {"0", ""} ]&
Run Code Online (Sandbox Code Playgroud)
我必须使用数字4来获得与"%05d"相似的结果,这很奇怪.我根本不明白这种行为.有人可以向我解释一下吗?
它是实现我曾经在bash中使用的最佳方式吗?
我不会用PaddedForm这个.事实上,我不确定这PaddedForm对任何事都有好处.相反,我会使用旧的ToString,Characters并且PadLeft,像这样:
toFixedWidth[n_Integer, width_Integer] :=
StringJoin[PadLeft[Characters[ToString[n]], width, "0"]]
Run Code Online (Sandbox Code Playgroud)
然后你可以使用StringForm和ToString创建你的文件名:
toNumberedFileName[n_Integer] :=
ToString@StringForm["filename_``", toFixedWidth[n, 5]]
Run Code Online (Sandbox Code Playgroud)
Mathematica不太适合这种弦乐变换.
编辑添加: Mathematica本身不具备所需的功能,但java.lang.String该类具有静态方法format(),该方法采用printf-style参数.您可以非常轻松地使用Mathematica的JLink功能调用它.性能不会很好,但对于许多用例,你不会那么在意:
Needs["JLink`"];
LoadJavaClass["java.lang.String"];
LoadJavaClass["java.util.Locale"];
sprintf[fmt_, args___] :=
String`format[Locale`ENGLISH,fmt,
MakeJavaObject /@
Replace[{args},
{x_?NumericQ :> N@x,
x : (_Real | _Integer | True |
False | _String | _?JavaObjectQ) :> x,
x_ :> MakeJavaExpr[x]},
{1}]]
Run Code Online (Sandbox Code Playgroud)
你需要做更多的工作,因为JLink对于具有可变数量参数的Java函数有点愚蠢.该format()方法采用格式字符串和Java数组Object,Mathematica不会自动进行转换,这MakeJavaObject就是它的用途.
我遇到了相同的问题,并决定编写自己的函数.我没有在Java中这样做,而只是在Mathematica中使用了字符串操作.结果很长,因为我实际上也需要%f功能,但它可以工作,现在我把它作为一个包,我可以随时使用.这是GitHub项目的链接:
https://github.com/vlsd/MathPrintF
它附带安装说明(实际上只是复制$ Path中的某个目录).
希望这对至少一些人有所帮助.
您还可以定义一个函数,它将所有参数传递给StringForm []并使用IntegerString或填充函数,如前所述:
Sprintf[args__] := StringForm[args__] // ToString;
file = Sprintf["filename_``", IntegerString[n, 10, 5]];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5331 次 |
| 最近记录: |