R: Как получить имя файла с Quanteda: char_segment - PullRequest
0 голосов
/ 05 июля 2018

Я использую char_segment из библиотеки Quanteda, чтобы отделить несколько документов от одного файла, разделенного шаблоном, эта команда отлично работает и легко! (Я пробовал с str_match и strsplit, но безуспешно).

К сожалению, я не могу получить имя файла как переменную, это ключ к следующему анализу. пример

Пример моих команд:

Library(quanteda)
doc <- readtext(paste0("PATH/*.docx"))
View(doc)

docc=char_segment(doc$text,  pattern = ",", remove_pattern = TRUE)

Пожалуйста, любые предложения или другие варианты разделения документов приветствуются.

Ответы [ 3 ]

0 голосов
/ 06 июля 2018

У вас уже должны быть имена файлов Word:

require(readtext)
data_dir <- system.file("extdata/", package = "readtext")
readtext(paste0(data_dir, "/word/*"))

readtext object consisting of 6 documents and 0 docvars.    
# data.frame [6 × 2]
  doc_id                                 text                
  <chr>                                  <chr>               
1 21Parti_Socialiste_SUMMARY_2004.doc    "\"[pic]\nRésu\"..."
2 21vivant2004.doc                       "\"http://www\"..." 
3 21VLD2004.doc                          "\"http://www\"..." 
4 32_socialisti_democratici_italiani.doc "\"DIVENTARE \"..." 
5 UK_2015_EccentricParty.docx            "\"The Eccent\"..." 
6 UK_2015_LoonyParty.docx                "\"The Offici\"..."

Они передаются нижестоящим объектам quanteda в качестве имен документов.

0 голосов
/ 06 июля 2018

Пример, когда я читаю текст Это моя проблема, когда я разделяю документы на ### *

Когда я использую сегмент Char

0 голосов
/ 05 июля 2018

Просто сначала получите список ваших файлов docx, он выдаст имена файлов. Затем запустите на них функцию char_segment с помощью lapply, loop или purrr :: map ()

В следующем коде предполагается, что ваши целевые документы хранятся в каталоге с именем "docx" в вашем рабочем каталоге.

library(quanteda)
library(readtext)  ## Remember to include in your posts the libraries required to replicate the code.


list_of_docx <- list.files(path = "./docx", ## Looks inside the ./docx directory
                       full.names = TRUE,   ## retrieves the full path to the documents
                       pattern = "[.]docx$", ## retrieves al documents whose names ends in ".docx"
                       ignore.case = TRUE)  ## ignores the letter case of the document's names

Подготовка к циклу

df_docx <- data.frame() ## Create an empty dataframe to store your data

for (d in seq_along(list_of_docx)) {  ## Tell R to run the loop/iterate along the number of elements within thte list of doccument paths
    temp_object <-readtext(list_of_docx[d])
    temp_segmented_object <- char_segment(temp_object$text, pattern = ",", remove_pattern = TRUE)
    temp_df <- as.data.frame(temp_segmented_object)
    colnames(temp_df) <- "segments"
    temp_df$title <- as.character(list_of_docx[d])  ## Create a variable with the title of the source document
    temp_df <- temp_df[, c("title", "segments")]
    df_docx <- rbind(df_docx, temp_df) ## Append each dataframe to the previously created empty dataframe
    rm(temp_df, temp_object, d)
    df_docx
 }


head(df_docx)
...