Sparlyr,dplyr,regex提取模式形成文本变量,然后用分号分隔

时间:2018-11-12 14:38:41

标签: r regex dplyr sparklyr

我正在使用sparklyr和dplyr,并且我一直在尝试创建一个变量extract_code,该变量将从文本变量中提取某种模式。 模式是3个字母+ 3个数字。该模式可以在同一文本中出现多次。 在这种情况下,我希望模式之间用分号

分隔

我已经使用正则表达式创建了该对象:

regex_pattern <- "[A-Za-z]{3}[0-9]{3}"

这里是:

test <-  data.table(id = 1:3, text= c("(table 012 APM325)", "(JUI524 toto KIO879)" , "(pink car in the field KJU547 MPO362/JHY879)"))

这就是我想要的东西:

test <-   data.table(id = 1:3, text= c("(table 012 APM325)", "(JUI524 toto KIO879)" , "(pink car in the field KJU547 MPO362/JHY879)"), extract_code =c( "APM325", "JUI524;KIO879" , "KJU547;MPO362;JHY879"))

我已经尝试过了:

test <- test %>%  mutate(extract_code = regexp_extract(text, regex_pattern, 0))

data.table(id = 1:3, text= c("(table 012 APM325)", "(JUI524 toto KIO879)" , "(pink car in the field KJU547 MPO362/JHY879)"), extract_code =c( "APM325", "JUI524" , "KJU547"))

但是我只有第一个模式。

您有什么建议吗?谢谢!

编辑:此工作!

try <-  data.table(id = 1:3, text= c("(table 012 APM325)", "(JUI524 toto KIO879)" , "(pink car in the field KJU547 MPO362/JHY879)"))

sdf_try <- copy_to(sc, try , "try" )

extract.pattern <- function(pat) function(df) {
   f <- function(vec)  sapply(regmatches(vec, gregexpr(pat, vec)), paste0, collapse = ";")
   dplyr::mutate(df, extract_code = f(text))
 }

 sdf_try %>%
   spark_apply(extract.pattern("[A-Z]{3}[0-9]{3}"))

但这不起作用:

regex_pattern <- "[A-Z]{3}[0-9]{3}"


sdf_try %>%
   spark_apply(extract.pattern(regex_pattern))

# Error: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 8.0 failed 4 times, most recent failure: Lost task 0.3 in stage 8.0 Exception: sparklyr worker rscript failure with status 255, check worker logs for details.


sdf_try %>%
   spark_apply(extract.pattern('regex_pattern'))

1 个答案:

答案 0 :(得分:-1)

regex_pattern <- "[A-Z]{3}[0-9]{3}"
test %>%  mutate(extract_code = sapply(regmatches(text, gregexpr(regex_pattern,text)), paste0, collapse = ";"))

#  id                                         text         extract_code
#1  1                           (table 012 APM325)               APM325
#2  2                         (JUI524 toto KIO879)        JUI524;KIO879
#3  3 (pink car in the field KJU547 MPO362/JHY879) KJU547;MPO362;JHY879

  • 我已将[A-Za-z]更改为[A-Z]。如果这对您不起作用,请更正。确实在示例中确实如此。

  • regmatches返回匹配列表。然后,我将它们折叠成由;分隔的单个字符串。