【问题标题】:Sparlyr, dplyr, regex extract pattern form a text variable then separated with semicolonSparklyr、dplyr、regex 从文本变量中提取模式,然后用分号分隔
【发布时间】:2018-11-12 14:38:40
【问题描述】:

我正在使用 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'))

【问题讨论】:

    标签: r regex dplyr sparklyr


    【解决方案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 返回匹配列表。然后我将它们折叠成由;分隔的单个字符串。

    【讨论】:

    • 非常感谢。不幸的是,我收到这条消息: UseMethod("escape") 中的错误:没有适用于 'escape' 的方法应用于类 "function" 的对象,因为我认为 'sapply' 与 sparklyr 不兼容。您的代码在本地使用 R 数据框,但在使用 spark 上下文的分布式 R 中似乎不起作用
    猜你喜欢
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多