对此无需使用tm,这是一个可重现的示例,它制作了一个包含 6000 行和两列的 CSV 文件,将其读入,然后将其转换为 6000 个 txt 文件
先为示例准备一些数据...
# from http://hipsum.co/?paras=4&type=hipster-centric
txt <- "Brunch single-origin coffee photo booth, meggings fixie stumptown pickled mumblecore slow-carb aesthetic ennui Odd Future blog plaid Bushwick. Seitan keffiyeh hashtag Portland, kitsch irony authentic vegan post-ironic. Actually pop-up flexitarian kale chips ethical authentic, stumptown meggings. Photo booth Helvetica farm-to-table Neutra. Selfies blog swag, lomo viral meh chillwave distillery deep v Truffaut. Squid Cosby sweater irony, art party mustache Vice Wes Anderson Bushwick McSweeney's locavore roof party paleo. 3 wolf moon salvia gentrify, taxidermy street art banh mi Portland deep v small batch Truffaut."
# get n random samples of this paragraph
n <- 6000
txt_split <- unlist(strsplit(txt, split = " "))
txts <- sapply(1:n, function(i) paste(sample(txt_split, 10, replace = TRUE),
collapse = " "))
# make dataframe then CSV file, two cols, n rows.
my_csv <- data.frame( col_one = 1:n,
col_two = txts)
write.csv(my_csv, "my_csv.csv", row.names = FALSE, quote = TRUE)
现在我们有一个 CSV 文件,可能与您的文件类似,我们可以将其读入:
# Read in the CSV file...
x <- read.csv("my_csv.csv", header = TRUE, stringsAsFactors = FALSE)
现在我们可以将 CSV 文件的每一行写入一个单独的文本文件(它们将出现在您的工作目录中):
# Write each row of the CSV to a txt file
sapply(1:nrow(x), function(i) write.table(paste(x[i,], collapse = " "),
paste0("my_txt_", i, ".txt"),
col.names = FALSE, row.names = FALSE))
如果你真的想使用tm,那你就在正确的轨道上,这对我来说很好:
# Read in the CSV file...
x <- read.csv("my_csv.csv", header = TRUE, stringsAsFactors = FALSE)
library(tm)
my_corpus <- Corpus(DataframeSource(x))
writeCorpus(my_corpus)
更接近你的例子对我来说也很好:
corp <- Corpus(VectorSource(x$col_one))
writeCorpus(corp)
如果它不适合您,则可能是您的 CSV 文件出现了一些异常情况、一些奇怪的字符等等。如果没有关于您的具体问题的更多细节,很难说。