java - 是否有用于解析 gettext PO 文件的 Java 库?

标签 java api scala gettext po

有人知道可以让我解析 .PO 文件的 Java 库吗?我只是想创建一个 ID 和值的映射,以便将它们加载到数据库中。

最佳答案

我搜索了互联网,也找不到现有的图书馆。如果您使用 Scala,由于其解析器组合器功能,您自己编写解析器非常容易。

调用PoParser.parsePo("po文件内容")。结果是 Translation 的列表。

我已经把这段代码做成了一个库(任何 JVM 语言都可以使用,当然包括 Java!): https://github.com/ngocdaothanh/scaposer

import scala.util.parsing.combinator.JavaTokenParsers

trait Translation

case class SingularTranslation(
  msgctxto: Option[String],
  msgid:    String,
  msgstr:   String) extends Translation

case class PluralTranslation(
  msgctxto:    Option[String],
  msgid:       String,
  msgidPlural: String,
  msgstrNs:    Map[Int, String]) extends Translation

// http://www.gnu.org/software/hello/manual/gettext/PO-Files.html
object PoParser extends JavaTokenParsers {
  // Removes the first and last quote (") character of strings
  // and concats them.
  private def unquoted(quoteds: List[String]): String =
    quoteds.foldLeft("") { (acc, quoted) =>
      acc + quoted.substring(1, quoted.length - 1)
    }

  // Scala regex is single line by default
  private def comment = rep(regex("^#.*".r))

  private def msgctxt = "msgctxt" ~ rep(stringLiteral) ^^ {
    case _ ~ quoteds => unquoted(quoteds)
  }

  private def msgid = "msgid" ~ rep(stringLiteral) ^^ {
    case _ ~ quoteds => unquoted(quoteds)
  }

  private def msgidPlural = "msgid_plural" ~ rep(stringLiteral) ^^ {
    case _ ~ quoteds => unquoted(quoteds)
  }

  private def msgstr = "msgstr" ~ rep(stringLiteral) ^^ {
    case _ ~ quoteds => unquoted(quoteds)
  }

  private def msgstrN = "msgstr[" ~ wholeNumber ~ "]" ~ rep(stringLiteral) ^^ {
    case _ ~ number ~ _ ~ quoteds => (number.toInt, unquoted(quoteds))
  }

  private def singular =
    (opt(comment) ~ opt(msgctxt) ~
     opt(comment) ~ msgid ~
     opt(comment) ~ msgstr ~ opt(comment)) ^^ {
    case _ ~ ctxto ~ _ ~ id ~ _ ~ s ~ _ =>
      SingularTranslation(ctxto, id, s)
  }

  private def plural =
    (opt(comment) ~ opt(msgctxt) ~
     opt(comment) ~ msgid ~
     opt(comment) ~ msgidPlural ~
     opt(comment) ~ rep(msgstrN) ~ opt(comment)) ^^ {
    case _ ~ ctxto ~ _ ~ id ~ _ ~ idp ~ _ ~ tuple2s ~ _ =>
      PluralTranslation(ctxto, id, idp, tuple2s.toMap)
  }

  private def exp = rep(singular | plural)

  def parsePo(po: String): List[Translation] = {
    val parseRet = parseAll(exp, po)
    if (parseRet.successful) parseRet.get else Nil
  }
}

关于java - 是否有用于解析 gettext PO 文件的 Java 库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4635721/

相关文章:

scala - Scala 中固有层次结构中的对象初始化序列

java - 如何使用 JPA 查询在同一字段中选择可变数量的相似字符串?

android - 索尼智能扩展 API 设备支持?

java - 如何在 Android 中发出并处理一个 Http 请求,并给出一个 json 文件作为响应?

scala - 是否可以判断一个类是在 Java 还是在 Scala 中实现的?

list - 在满足谓词的每个元素处拆分列表(Scala)

java - 无法在包内找到或加载主类

java - 创建具有不同属性的对象

java - 将带有列表的 hibernate POJO 隐藏为可序列化的 rpc 返回对象

python - 从 instagram 的 api 获取趋势标签