我建议两种选择:
正则表达式替换仅保留前 2 行
如果您的前两行包含您需要的内容,那么只需使用提取前两行的正则表达式来提取它们。这比循环快。
@rconradin 的解决方案有效,但正如您将在 ?corpus 中指出的那样,我们强烈反对直接访问语料库对象的内部结构(因为它很快就会改变)。不循环也更快。
# test corpus for demonstration
testcorp <- corpus(c(
d1 = "This is doc1, line 1.\nDoc1, Line 2.\nLine 3 of doc1.",
d2 = "This is doc2, line 1.\nDoc2, Line 2.\nLine 3 of doc2."
))
summary(testcorp)
## Corpus consisting of 2 documents.
##
## Text Types Tokens Sentences
## d1 12 17 3
## d2 12 17 3
现在只用前两行覆盖文本。(这也会丢弃第二个换行符,如果您想保留它,只需将其移动到第一个捕获组。)
texts(testcorp) <-
stringi::stri_replace_all_regex(texts(testcorp), "(.*\\n.*)(\\n).*", "$1")
## Corpus consisting of 2 documents.
##
## Text Types Tokens Sentences
## d1 10 12 2
## d2 10 12 2
texts(testcorp)
## d1 d2
## "This is doc1, line 1.\nDoc1, Line 2." "This is doc2, line 1.\nDoc2, Line 2."
使用corpus_segment()
:
另一种解决方案是使用corpus_segment()
:
testcorp2 <- corpus_segment(testcorp, what = "other", delimiter = "\\n",
valuetype = "regex")
summary(testcorp2)
## Corpus consisting of 6 documents.
##
## Text Types Tokens Sentences
## d1.1 7 7 1
## d1.2 5 5 1
## d1.3 5 5 1
## d2.1 7 7 1
## d2.2 5 5 1
## d2.3 5 5 1
# get the serial number from each docname
docvars(testcorp2, "sentenceno") <-
as.integer(gsub(".*\\.(\\d+)", "\\1", docnames(testcorp2)))
summary(testcorp2)
## Corpus consisting of 6 documents.
##
## Text Types Tokens Sentences sentenceno
## d1.1 7 7 1 1
## d1.2 5 5 1 2
## d1.3 5 5 1 3
## d2.1 7 7 1 1
## d2.2 5 5 1 2
## d2.3 5 5 1 3
testcorp3 <- corpus_subset(testcorp2, sentenceno <= 2)
texts(testcorp3)
## d1.1 d1.2 d2.1 d2.2
## "This is doc1, line 1." "Doc1, Line 2." "This is doc2, line 1." "Doc2, Line 2."