问题描述
我一直致力于通过 R 中的 Quenteda 包识别和分类搭配。
例如;
我从文档列表中创建令牌对象,并应用搭配分析。
toks <- tokens(text$abstracts)
collocations <- textstat_collocations(toks)
但是,据我所知,没有一种明确的方法来查看哪些搭配频繁/存在于哪个文档中。即使我应用 kwic(toks,pattern = phrase(collocations),selection = 'keep'
) 结果也只会包含 rowid 作为 text1、text2 等。
我想根据 docvars 对搭配分析结果进行分组。 Quanteda 有可能吗?
解决方法
听起来您希望按文档统计搭配。 textstat_collocations()
的输出已经为每个搭配提供了计数,但这些是针对整个语料库的。
因此按文档(或任何其他变量)分组的解决方案是
- 使用
textstat_collocations()
获取搭配。下面是我在删除停用词和标点符号后完成的。 - 使用
tokens_compound()
组合形成停用词的标记。这会将每个搭配序列转换为单个标记。 - 从复合标记形成 dfm,并使用
textstat_frequency()
按文档计算复合。 这有点棘手
使用内置的就职语料库实现:
library("quanteda")
## Package version: 3.0
## Unicode version: 13.0
## ICU version: 69.1
## Parallel computing: 12 of 12 threads used.
## See https://quanteda.io for tutorials and examples.
library("quanteda.textstats")
toks <- data_corpus_inaugural %>%
tail(10) %>%
tokens(remove_punct = TRUE,padding = TRUE) %>%
tokens_remove(stopwords("en"),padding = TRUE)
colls <- textstat_collocations(toks)
head(colls)
## collocation count count_nested length lambda z
## 1 let us 34 0 2 6.257000 17.80637
## 2 fellow citizens 14 0 2 6.451738 16.18314
## 3 fellow americans 15 0 2 6.221678 16.16410
## 4 one another 14 0 2 6.592755 14.56082
## 5 god bless 15 0 2 8.628894 13.57027
## 6 united states 12 0 2 9.192044 13.22077
现在我们将它们复合并只保留搭配,然后通过文档获取频率:
dfmat <- tokens_compound(toks,colls,concatenator = " ") %>%
dfm() %>%
dfm_keep("* *")
那个 dfm 已经包含了每个搭配的文档计数,但是如果你想要一个 data.frame 格式的计数,有一个分组选项,使用 textstat_frequency()
。在这里,我只按文档输出了前两个,但是如果您删除 n = 2
,那么它将为您提供按文档所有搭配的频率。
textstat_frequency(dfmat,groups = docnames(dfmat),n = 2) %>%
head(10)
## feature frequency rank docfreq group
## 1 nuclear weapons 4 1 1 1985-Reagan
## 2 human freedom 3 2 1 1985-Reagan
## 3 new breeze 4 1 1 1989-Bush
## 4 new engagement 3 2 1 1989-Bush
## 5 let us 7 1 1 1993-Clinton
## 6 fellow americans 4 2 1 1993-Clinton
## 7 let us 6 1 1 1997-Clinton
## 8 new century 6 1 1 1997-Clinton
## 9 nation's promise 2 1 1 2001-Bush
## 10 common good 2 1 1 2001-Bush
,
构建 DFM · 选择特征 · 查找字典 · 分组文档 ... 搭配分析使我们能够Asia Heavens 识别单词的连续搭配。 ... 是专有名词,可以简单地根据英文文本的大小写来识别