1) 这里有一些问题,所以第一个选项删除了前两行:
sub("^categor([^\n]*\n){2}", "", text)
## [1] "At the end of the day, the criminal Valjean escaped once more."
如果categor 部分无关紧要,那么这样做:
tail(strsplit(text, "\n")[[1]], -2)
## [1] "At the end of the day, the criminal Valjean escaped once more."
2) 如果想要删除...:....\n 形式的任何行,其中每行冒号前的字符必须是单词字符:
gsub("\\w+:[^\n]+\n", "", text)
## [1] "At the end of the day, the criminal Valjean escaped once more."
或
gsub("\\w+:.+?\n", "", text)
## [1] "At the end of the day, the criminal Valjean escaped once more."
或
grep("^\\w+:", unlist(strsplit(text, "\n")), invert = TRUE, value = TRUE)
## [1] "At the end of the day, the criminal Valjean escaped once more."
3) 或者如果我们想删除只有特定标签的行:
gsub("(categories|Tags):.+?\n", "", text)
## [1] "At the end of the day, the criminal Valjean escaped once more."
4)如果您还想捕获标签,使用read.dcf 可能也很有趣。
s <- unlist(strsplit(text, "\n"))
ix <- grep("^\\w+:", s, invert = TRUE)
s[ix] <- paste("Content", s[ix], sep = ": ")
out <- read.dcf(textConnection(s))
给出这个 3 列矩阵:
> out
categories Tags
[1,] "crime, punishment, france" "valjean, javert,les mis"
Content
[1,] "At the end of the day, the criminal Valjean escaped once more."