0

我有一个包含 2 列、文档和文本的数据框

DOCS    TEXT
1   tanaman jagung seumur jagung 
2   tanaman jagung kacang ketimun rusak dimakan kelinci 
3   ladang diserbu kelinci tanaman jagung kacang ketimun rusak dimakan 
4   ladang diserbu kelinci tanaman jagung kacang ketimun rusak dimakan 
5   ladang diserbu kelinci tanaman jagung kacang ketimun rusak 

我想让多个文件 .txt 的数量与 id 的数量一样多,并且每个文件都包含不同的内容(每个 1 txt 文件在一列 TEXT 中包含 1 行文本)。因此,如果我有 5 个 Docs-> 5 个具有不同内容的文件 .txt

我已经尝试过这段代码

for (j in 1:nrow(dataframe)) {
         mytitle <- format("docs")
         myfile <- file.path(getwd(), paste0(mytitle, "_", j, ".txt"))
         write.table(dataframe$TEXT, file = myfile, sep = "", row.names = FALSE, col.names = FALSE,
                     quote = FALSE, append = FALSE)
        }

但是,结果包含 5 个 file.txt,每个文件具有相同的内容,其中包含“TEXT”列中的所有行。

4

2 回答 2

0

每个文件包含相同的原因是您每次都写入整个 TEXT 列。以下代码生成 5 个不同的文件:

 for (i in 1:nrow(dataframe)) {
       myfile <- file.path(paste0("docs_", i, ".txt"))
       file.cont <- strsplit(dataframe$TEXT[i]," ")
       write.table(file.cont, file = myfile, sep = "", row.names = FALSE,
                   col.names = FALSE, quote = FALSE)
 }

如您所见,我通过i从数据框 ( dataframe$TEXT[i]) 中选择第 th 行来创建文件内容。然后我使用 . 将字符串分成几个字符串strsplit。这样可以确保每个单词都打印在自己的行上。

另外,我创建的文件名与您不同。我不明白你对format(). 我把所有东西都放在一条线上。无需包含getwd()在路径中,因为 R 无论如何都会写入您的工作目录。

于 2015-05-14T06:29:57.327 回答
0

我建议您也尝试以下方法,而不是使用可能让您感到困惑的 for 循环

# Create a data frame 
DOCS <- c(1:5)
TEXT <- c("tanaman jagung seumur jagung " , 
          "tanaman jagung kacang ketimun rusak dimakan kelinci" , 
          "ladang diserbu kelinci tanaman jagung kacang ketimun rusak dimakan" , 
          "ladang diserbu kelinci tanaman jagung kacang ketimun rusak dimakan" , 
          "ladang diserbu kelinci tanaman jagung kacang ketimun rusak ")

df <- data.frame(DOCS , TEXT , Test)

# Convert to matrix 
M <- as.matrix(df)

# Create a function that will write every single file
write_file <- function(file){
  my_title <- format("docs")  
  file_name <- file.path(paste0( my_title , "_" , file[1] , ".txt"))
  file_content <- file[2]
  write.table(file_content , file = file_name , append = F , row.names = F 
  , col.names = F , quote = F)

}

# Use the apply function to pass each row in matrix to the 
# function that creates every single file

apply(M , 1 , write_file)
于 2015-05-14T07:46:04.317 回答