Функция стемминга в r - PullRequest
       65

Функция стемминга в r

0 голосов
/ 07 апреля 2020

Пакет corpus предоставляет пользовательскую функцию stemming Функция стемминга должна, когда дан термин в качестве входных данных, возвращать стебель термина в качестве выходных данных.

Из Слова для терминации Я взял следующий пример, в котором используется hunspell словарь для выполнения стволов.

Сначала я определю предложения, для которых проверяется эта функция:

sentences<-c("The color blue neutralizes orange yellow reflections.", 
             "Zod stabbed me with blue Kryptonite.", 
             "Because blue is your favourite colour.",
             "Red is wrong, blue is right.",
             "You and I are going to yellowstone.",
             "Van Gogh looked for some yellow at sunset.",
             "You ruined my beautiful green dress.",
             "You do not agree.",
             "There's nothing wrong with green.")

Пользовательская функция стволов:

stem_hunspell <- function(term) {
  # look up the term in the dictionary
  stems <- hunspell::hunspell_stem(term)[[1]]

  if (length(stems) == 0) { # if there are no stems, use the original term
    stem <- term
  } else { # if there are multiple stems, use the last one
    stem <- stems[[length(stems)]]
  }

  stem
}

Этот код

sentences=text_tokens(sentences, stemmer = stem_hunspell)

производит:

> sentences
[[1]]
[1] "the"        "color"      "blue"       "neutralize" "orange"     "yellow"    
[7] "reflection" "."         

[[2]]
[1] "zod"        "stabbed"    "me"         "with"       "blue"       "kryptonite"
[7] "."         

[[3]]
[1] "because"   "blue"      "i"         "your"      "favourite" "colour"   
[7] "."        

[[4]]
[1] "re"    "i"     "wrong" ","     "blue"  "i"     "right" "."    

[[5]]
[1] "you"         "and"         "i"           "are"         "go"         
[6] "to"          "yellowstone" "."          

[[6]]
[1] "van"    "gogh"   "look"   "for"    "some"   "yellow" "at"     "sunset" "."     

[[7]]
[1] "you"       "ruin"      "my"        "beautiful" "green"     "dress"    
[7] "."        

[[8]]
[1] "you"   "do"    "not"   "agree" "."    

[[9]]
[1] "there"   "nothing" "wrong"   "with"    "green"   "." 

После завершения я хотел бы применить к тексту другие операции, например удаление стоп-слов. В любом случае, когда я применил к своим предложениям функцию tm:

removeWords(sentences,stopwords)

, я получил следующую ошибку:

Error in UseMethod("removeWords", x) : 
 no applicable method for 'removeWords' applied to an object of class "list"

Если я использую

unlist(sentences)

Я не получаю желаемого результата, потому что получаю chr из 65 элементов. Желаемый результат должен быть (например, для первых предложений):

"the color blue neutralize orange yellow reflection."       

Ответы [ 2 ]

1 голос
/ 07 апреля 2020

Мы можем использовать map

library(tm)
library(purrr)
map(sentences, removeWords, stopwords())
#[[1]]
#[1] ""           "color"      "blue"       "neutralize" "orange"     "yellow"     "reflection"
#[8] "."         

#[[2]]
#[1] "zod"        "stabbed"    ""           ""           "blue"       "kryptonite" "."     
1 голос
/ 07 апреля 2020

Если вы хотите удалить стоп-слова из каждого sentence, вы можете использовать lapply:

library(tm)
lapply(sentences, removeWords, stopwords())

#[[1]]
#[1] ""           "color"      "blue"       "neutralize" "orange"     "yellow"     "reflection" "."         

#[[2]]
#[1] "zod"        "stabbed"    ""           ""           "blue"       "kryptonite" "."  
#...
#...

Однако из ожидаемого результата вы видите, что хотите вставить текст вместе.

lapply(sentences, paste0, collapse = " ")

#[[1]]
#[1] "the color blue neutralize orange yellow reflection ."

#[[2]]
#[1] "zod stabbed me with blue kryptonite ."
#....
...