将R代码移植到Python

时间:2014-12-11 00:06:12

标签: python r porting

我正在寻找一种将R代码移植到Python的方法。我想知道是否有人知道某种方式进行粗略翻译,以方便移植。请注意,我对从Python运行R或从R运行Python不感兴趣 - 我希望从现有的R代码中使用本机Python。我在R中编写了一些自动翻译几种语言功能的函数:

  gsub.R.to.python <- function(x)
  {
        #  very crude conversion of R code to python - facilitating manual port
        out <- gsub.function.to.def(x)
        out <- gsub(pattern = "<-","=",out)
        out <- gsub.dots.to.underscore(out)
        out <- gsub.python.remove.brackets(out)
        out <- gsub.T.to.True(out)
        out <- gsub.F.to.False(out)
        cat(out)
        invisible(out)
  }

  gsub.dots.to.underscore <- function(x)
  {
        #  replace dots to underscores in variable names (i.e. between letters)
        # gsub.dots.to.underscore(c("a.b","1.0")) -->  "a_b" "1.0"
        out <- gsub(pattern = "(?<=[a-zA-Z])\\.(?=[a-zA-Z])","_",x,perl = T)
        return(out)
  }

  gsub.function.to.def <- function(x)
  {
        #  change all function lines - use perl multiline searching
        out <- gsub("(?m)^([a-zA-Z].+?) <- function\\((.+?)\\)","def \\1(\\2):",x,perl = T)
        return(out)
  }

  gsub.python.remove.brackets<- function(x)
  {
        #  get rid of brackets on their own lines
        out <- gsub("(?m)^\\s*\\{\\s*$","",x,perl = T)
        out <- gsub("(?m)^\\s*\\}\\s*$","",out,perl = T)
        return(out)
  }

  gsub.T.to.True <- function(x) gsub("\\bT\\b|\\bTRUE\\b","True",x)
  gsub.F.to.False <- function(x) gsub("\\bF\\b|\\bFALSE\\b","False",x)

在一个R代码块上运行gsub.R.to.python()会产生一个Python-ish乱码块,它更容易转换为Python。我正在寻找更好/更完整版本的这个想法,或者其他一些工具来帮助移植过程。

例如,在代码本身的R中运行此代码会产生以下结果:

  def gsub_R_to_python(x):

        #  very crude conversion of R code to python - facilitating manual port
        out = gsub_function_to_def(x)
        out = gsub(pattern = "=","=",out)
        out = gsub_dots_to_underscore(out)
        out = gsub_python_remove_brackets(out)
        out = gsub_T_to_True(out)
        out = gsub_F_to_False(out)
        cat(out)
        invisible(out)

  def gsub_dots_to_underscore(x):

        #  replace dots to underscores in variable names (i_e. between letters)
        # gsub_dots_to_underscore(c("a_b","1.0")) -->  "a_b" "1.0"
        out = gsub(pattern = "(?<=[a-zA-Z])\.(?=[a-zA-Z])","_",x,perl = True)
        return(out)

  def gsub_function_to_def(x):

        #  change all function lines - use perl multiline searching
        out = gsub("(?m)^([a-zA-Z].+?) = function\((.+?)\)","def \1(\2):",x,perl = True)
        return(out)

  gsub_python_remove_brackets= function(x)

        #  get rid of brackets on their own lines
        out = gsub("(?m)^\s*\{\s*$","",x,perl = True)
        out = gsub("(?m)^\s*\}\s*$","",out,perl = True)
        return(out)

  def gsub_T_to_True(x): gsub("\bT\b|\bTRUE\b","True",x)
  def gsub_F_to_False(x): gsub("\bF\b|\bFALSE\b","False",x)

0 个答案:

没有答案