在 R 中为 NLP 字符串编写函数
Write function for NLP String in R
这是我已经问过的一个问题的变体,但我认为有一个问题需要单独提出一个问题。我使用 R 来清理一些文本文件。这些是字母,即字符串。我正在使用 NLP,所以这些是 NLP 字符串,而不是基本 R 字符串。简化版本如下所示:
library(NLP)
letter1 <- as.String(c("here is some text"))
letter2 <- as.String(c("and here is some more text"))
letter3 <- as.String(c("and this is the final one"))
list <- list(letter1 = letter1, letter2 = letter2, letter3 = letter3)
当我要导出这些文本文件时出现问题。 (我希望每个字母都在一个单独的文本文件中,文件名与其在列表中的名称相对应。)鉴于先前问题中发布的解决方案,我使用了以下内容:
for (i in 1:length(list)) {
write.csv(list[i], file=paste0("~/desktop/", names(list)[i]))
}
执行此操作时,我收到一条错误消息 cannot coerce class ""String"" to a data.frame
。所以我将它们转换为基本 R 字符串,如下所示:
list2 <- lapply(list, function(x){
x = toString(x)
x
})
这几乎行得通。但是,输出看起来像这样(对于第一个):
"","letter1"
"1","here is some text"
我只要here is some text
。我不想 "", "letter1", or "1," or the quotation marks around
这里有一些文字`。这可能吗?
我的示例一定与我自己的数据有所不同。对于我的数据,最简单的解决方案是使用 cat()
,尽管这不适用于上面的示例。我要 post 在这里回答,但以防它对任何人有帮助。我不确定我是否确定要编辑示例或保持原样以反映实际历史。
这是我已经问过的一个问题的变体,但我认为有一个问题需要单独提出一个问题。我使用 R 来清理一些文本文件。这些是字母,即字符串。我正在使用 NLP,所以这些是 NLP 字符串,而不是基本 R 字符串。简化版本如下所示:
library(NLP)
letter1 <- as.String(c("here is some text"))
letter2 <- as.String(c("and here is some more text"))
letter3 <- as.String(c("and this is the final one"))
list <- list(letter1 = letter1, letter2 = letter2, letter3 = letter3)
当我要导出这些文本文件时出现问题。 (我希望每个字母都在一个单独的文本文件中,文件名与其在列表中的名称相对应。)鉴于先前问题中发布的解决方案,我使用了以下内容:
for (i in 1:length(list)) {
write.csv(list[i], file=paste0("~/desktop/", names(list)[i]))
}
执行此操作时,我收到一条错误消息 cannot coerce class ""String"" to a data.frame
。所以我将它们转换为基本 R 字符串,如下所示:
list2 <- lapply(list, function(x){
x = toString(x)
x
})
这几乎行得通。但是,输出看起来像这样(对于第一个):
"","letter1"
"1","here is some text"
我只要here is some text
。我不想 "", "letter1", or "1," or the quotation marks around
这里有一些文字`。这可能吗?
我的示例一定与我自己的数据有所不同。对于我的数据,最简单的解决方案是使用 cat()
,尽管这不适用于上面的示例。我要 post 在这里回答,但以防它对任何人有帮助。我不确定我是否确定要编辑示例或保持原样以反映实际历史。