2016-08-10 12 views
0

Ich habe einige Textzeichenfolgen, aus denen ich bestimmte Informationen extrahieren möchte. Insbesondere möchte ich die Bewertung von 10 aus extrahieren.R regex extract rating von 10 aus string

Ich würde Hilfe gerne in eine Funktion func_to_extract_rating Konstruktion, die die folgenden ...

text_string_vec <- c('blah$2.94 blah blah 3/10 blah blah.', 
        'foo foo 8/10.', 
        '10/10 bar bar21/09/2010 bar bar', 
        'jdsfs1/10djflks5/10.') 

func_to_extract_rating <- function(){} 

output <- lapply(text_string_vec,func_to_extract_rating) 
output 
[[1]] 
[1] 3 10 

[[2]] 
[1] 8 10 

[[3]] 
[1] 10 10 

[[4]] 
[[4]][[1]] 
[1] 1 10 

[[4]][[2]] 
[1] 5 10 
+0

'y <- regmatches (text_string_vec, gregexpr ('\\ d +/10', text_string_vec)); Rapply (y, strsplit, split = '/', wie = 'Liste') ' – rawr

Antwort

3

So etwas wie diese vielleicht:

library(stringr) 

result = str_extract_all(text_string_vec, "[0-9]{1,2}/10") 
result = lapply(result, function(x) gsub("/"," ", x)) 

[[1]] 
[1] "3 10" 

[[2]] 
[1] "8 10" 

[[3]] 
[1] "10 10" 

[[4]] 
[1] "1 10" "5 10" 

Aber da es immer von 10, wenn Sie nur Wollen Sie die numerische Bewertung, können Sie tun:

result = str_extract_all(text_string_vec, "[0-9]{1,2}/10") 
result = lapply(result, function(x) as.numeric(gsub("/10","", x))) 
1

Hier ist einOption

lapply(strsplit(str1, "([0-9]{1,2}\\/10)(*SKIP)(*FAIL)|.", perl = TRUE), 
     function(x) { 
     lst <- lapply(strsplit(x[nzchar(x)], "/"), as.numeric) 
     if(length(lst)==1) unlist(lst) else lst}) 
#[[1]] 
#[1] 3 10 

#[[2]] 
#[1] 8 10 

#[[3]] 
#[1] 10 10 

#[[4]] 
#[[4]][[1]] 
#[1] 1 10 

#[[4]][[2]] 
#[1] 5 10