简体   繁体   English

是否有与 Python 的 printf hash 等效的 Java 替代品?

[英]Is there a Java equivalent of Python's printf hash replacement?

Specifically I am converting a python script into a java helper method.具体来说,我将 python 脚本转换为 java 辅助方法。 Here is a snippet (slightly modified for simplicity).这是一个片段(为简单起见稍作修改)。

# hash of values
vals = {}
vals['a'] = 'a'
vals['b'] = 'b'
vals['1'] = 1

output = sys.stdout
file = open(filename).read()

print >>output, file % vals,

So in the file there are %(a), %(b), %(1) etc that I want substituted with the hash keys.所以在文件中有 %(a), %(b), %(1) 等我想用 hash 键代替。 I perused the API but couldn't find anything.我仔细阅读了 API 但找不到任何东西。 Did I miss it or does something like this not exist in the Java API?我错过了还是 Java API 中不存在类似的东西?

You can't do this directly without some additional templating library.如果没有一些额外的模板库,您将无法直接执行此操作。 I recommend StringTemplate .我推荐StringTemplate Very lightweight, easy to use , and very optimized and robust.非常轻巧,易于使用,并且非常优化和强大。

I doubt you'll find a pure Java solution that'll do exactly what you want out of the box.我怀疑你会找到一个纯粹的 Java 解决方案,它会完全满足你的要求。

With this in mind, the best answer depends on the complexity and variety of Python formatting strings that appear in your file:考虑到这一点,最佳答案取决于文件中出现的 Python 格式字符串的复杂性和多样性:

  • If they're simple and not varied, the easiest way might be to code something up yourself.如果它们简单且没有变化,最简单的方法可能是自己编写代码。

  • If the opposite is true, one way to get the result you want with little work is by embedding Jython into your Java program .如果情况正好相反,只需很少工作即可获得所需结果的一种方法是将 Jython 嵌入到 Java 程序中。 This will enable you to use Python's string formatting operator ( % ) directly.这将使您能够直接使用 Python 的字符串格式化运算符 ( % )。 What's more, you'll be able to give it a Java Map as if it were a Python dictionary ( vals in your code).更重要的是,您将能够给它一个 Java Map就好像它是一个 Python 字典(代码中的vals )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM