Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translation of R script using gettext

Is it possible to use something like gettext to translate an R script. If so, how? If not, what other options I have?

like image 451
evgeniuz Avatar asked May 26 '12 09:05

evgeniuz


1 Answers

You can use base::gettext/ngettext, base::bindtextdomain and tools::xgettext2pot functions.
For example:

myFunction <- function()
{  
  bindtextdomain("R-myProgram","/my/translation/dir")
  gettext("Hello",domain="R-myProgram")
}

Then, supposing this function is inside a file whose path is "/my/dir/R/myfile.R" use: tools::xgettext2pot("/my/dir", "/my/translation/dir/pot/R-myProgram.pot") then use msginit, msgfmt, etc. to create a .mo file /my/translation/dir/fr/LC_MESSAGES/R-myProgram.mo. myFunction() should now print "Bonjour" instead of "Hello" if your locale is French.

A couple of other points :

  • It seems like xgettext2pot assumes your project is a standard R package and looks only for *.R files inside the R/ subdirectory.
  • The domain argument seems to be by default the namespace of the function calling gettext()
  • stop(), message(), warning() and packupStartupMessage() are also detected by xgettext2pot. There is also a gettextf() function available as a sprintf-like variant of gettext().
  • Since the standard xgettext utility doesn't seem to support R syntax, and since one has to use tools::xgettext2pot, a couple of things will miss from the standard approach, such as message contexts (pgettext()), flags indicating printf-like strings and the possibility to write in-code comments for the translators (extracted by xgettext -c) without modifying the .pot file by hand.
like image 72
ehmicky Avatar answered Oct 06 '22 11:10

ehmicky