首页 > 解决方案 > 如何将(句子)单位定义为 quanteda 中的行?

问题描述

我想知道你是否可以改变句子的形成。我想要一个新行/新行来形成句子,而不是用标点符号来构成句子。

标签: rquanteda

解决方案


这是一个非常简单的问题,所以我将不得不在这里猜测您的意图,但我猜您想将文档分成几行而不是句子。有两种方法可以做到这一点:拥有一个新的语料库,其中每个句子都是一个文档,或者一个新的标记对象,其中每个“标记”是一行。

两者兼得是使用*_segment()功能的问题。这里有两种方法,我将创建一些示例文本,其中每行都是一个“句子”。

library("quanteda")
## Package version: 2.0.0

txt <- c(
  d1 = "Sentence one.\nSentence two is on this line.\nLine three",
  d2 = "This is a single sentence."
)
cat(txt)
## Sentence one.
## Sentence two is on this line.
## Line three This is a single sentence.

要将其转换为标记,我们使用char_segment()换行符作为分段模式,然后将其强制转换为列表,然后转换为标记:

# as tokens
char_segment(txt, pattern = "\n", remove_pattern = FALSE) %>%
  as.list() %>%
  as.tokens()
## Tokens consisting of 4 documents.
## d1.1 :
## [1] "Sentence one."
## 
## d1.2 :
## [1] "Sentence two is on this line."
## 
## d1.3 :
## [1] "Line three"
## 
## d2.1 :
## [1] "This is a single sentence."

如果要将每一行变成可以进一步分段的“文档”,则在从对象corpus_segment()构造语料库之后使用:txt

# as documents
corpus(txt) %>%
  corpus_segment(pattern = "\n", extract_pattern = FALSE)
## Corpus consisting of 4 documents.
## d1.1 :
## "Sentence one."
## 
## d1.2 :
## "Sentence two is on this line."
## 
## d1.3 :
## "Line three"
## 
## d2.1 :
## "This is a single sentence."

推荐阅读