通过运行一个循环的罚款和工作代码不起作用

问题描述 投票:0回答:1

从字符串:

"((VBD)(((JJ))(CC)((RB)(JJ)))((IN)((DT)(JJ)(NNP)(NNPS))))"

我需要以下内容:

"JJ", "RBJJ", "DTJJNNPNNPS", "JJCCRBJJ", "INDTJJNNPNNPS" "VBDJJCCRBJJINDTJJNNPNNPS"

(这是我刚才SO查询,这是由@布赖恩·迪格斯解决,请参考。“R:如何使用正则表达式内,最里面的括号区分”,如果需要的话)

所以我用下面的代码:

library("plotrix")
library("plyr")
strr<-c("((VBD)(((JJ))(CC)((RB)(JJ)))((IN)((DT)(JJ)(NNP)(NNPS))))")
tmp <- gsub("\\(([^\\(\\)]*)\\)",  '("\\1")', strr)
tmp <- gsub("\\(", "list(", tmp)
tmp <- gsub("\\)list", "),list", tmp)
tmp <- eval(parse(text=tmp))
atdepth <- function(l, d) {
if (d > 0 & !is.list(l)) {
 return(NULL)
}
 if (d == 0) {
 return(unlist(l))
 }
if (is.list(l)) {
 llply(l, atdepth, d-1)
 }
 }

 pastelist <- function(l) {paste(unlist(l), collapse="", sep="")}
 down <- llply(1:listDepth(tmp), atdepth, l=tmp)
 out <- if (length(down) > 2) {
 c(unlist(llply(length(down):3, function(i) {
 unlist(do.call(llply, c(list(down[[i]]), replicate(i-3, llply), pastelist)))
 })), unlist(pastelist(down[[2]]))) 
 } else {
 unlist(pastelist(down[[2]]))
 }
 out <- out[out != ""]

而我得到了我想要的东西,但它是不可能通过循环使用上面的代码来处理多个字符串(STRR等)在同一时间?我大致需要处理一串字符串,并在文件中收集。我想为包括环,但总是有距离的设置在出文件中的字符串的最后一个字符串结束。我应该如何通过运行一个循环的代码?字符串设置如下。

strr<-c("(((((NNS))((IN)((NNS)(CC)(NNS))))((VBD)((PRP))((IN)((NN))))))", 

"((((NNS))((VBD)((TO)(((NNP))((NNP))))((TO)((DT)(NNP))))))", 

"((((IN)(((NNP))((NNP))))((NNP)(NNP)(NNPW)(NNP))((VBD)((IN)((DT)(JJ)(NN)(NN))))))"
)
r regex loops
1个回答
0
投票

也许它可以在一个更聪明的方式进行修改,但一个简单的人会定义一个新的功能,并使用sapply()

### Nothing new
library("plotrix")
library("plyr")
strr<-c("(((((NNS))((IN)((NNS)(CC)(NNS))))((VBD)((PRP))((IN)((NN))))))", 
        "((((NNS))((VBD)((TO)(((NNP))((NNP))))((TO)((DT)(NNP))))))",   
        "((((IN)(((NNP))((NNP))))((NNP)(NNP)(NNPW)(NNP))((VBD)((IN)((DT)(JJ)(NN)(NN))))))")

strrr <- strr[rep(1:3,200)]

atdepth <- function(l, d) {
  if (d > 0 & !is.list(l)) {
    return(NULL)
  }
  if (d == 0) {
    return(unlist(l))
  }
  if (is.list(l)) {
    llply(l, atdepth, d-1)
  }
}
pastelist <- function(l) {paste(unlist(l), collapse="", sep="")}
###
### New function here
fun <- function(strr){
tmp <- gsub("\\(([^\\(\\)]*)\\)",  '("\\1")', strr)
tmp <- gsub("\\(", "list(", tmp)
tmp <- gsub("\\)list", "),list", tmp)
tmp <- eval(parse(text=tmp))

down <- llply(1:listDepth(tmp), atdepth, l=tmp)
out <- if (length(down) > 2) {
  c(unlist(llply(length(down):3, function(i) {
    unlist(do.call(llply, c(list(down[[i]]), replicate(i-3, llply), pastelist)))
  })), unlist(pastelist(down[[2]]))) 
} else {
  unlist(pastelist(down[[2]]))
}
out <- out[out != ""]
out
}

sapply(strr, fun)
© www.soinside.com 2019 - 2024. All rights reserved.