在 dfm (quanteda) 中操作(重命名和重组)特征

Manipulate (rename and recombine) features in a dfm (quanteda)

我想在 dfm 中操作(重命名和组合)特征,如何进行?

原因如下:我想使用与 Quanteda 中实现的 Porter 词干提取器不同的词干提取算法(通过 Python 调用的 kpss 算法)。

例子 三词句子 c("creatief creatieve creatie") 将产生具有三个特征(即 "creatief"、"creatieve"、"creatie")的 dfm,所有特征的词频均为 1 .但是,kpss算法会将这些词词干到"creatie"。如果我可以将 dfm 中的这三个特征组合成一个名为 "creatie" 且词频为三个的特征,那将非常方便。

非常感谢您的帮助。

(注意。 我知道在将 dfm 转换为 'simple' 矩阵后可以进行此类数据操作,但我想在 dfm 中执行此操作).

附录 我忽略了 dfm_compress 函数。我快到了......在我压缩了 dfm 之后,是否也可以应用字典,例如单词 'creati' 和 'innovati' 应该都算作单词类别 'creati' 的出现(参见 dfm 中的字典功能)? (注意。鉴于大量的 txts,我宁愿不喜欢阻止原始数据文件)

您可以通过创建 dfm 然后对特征进行词干提取,然后重新编译 dfm 以组合在词干提取后变得相同的特征来完成此操作。

require(quanteda)
txt <- c("creatief creatieve creatie")

(dfm1 <- dfm(txt))
## Document-feature matrix of: 1 document, 3 features (0% sparse).
## 1 x 3 sparse Matrix of class "dfmSparse"
##        features
## docs    creatief creatieve creatie
##   text1        1         1       1

这是我为您的示例近似计算的一个步骤,但是您可以将下面右侧的字符串子集函数替换为您自己对特征的字符向量进行的词干提取操作。

# this approximates what you can do with the Python-based stemmer
# note that here you must use colnames<- since there is no function
# featnames<- (for replacement)
colnames(dfm1) <- stringi::stri_sub(featnames(dfm1), 1, 7)
dfm1
## Document-feature matrix of: 1 document, 3 features (0% sparse).
## 1 x 3 sparse Matrix of class "dfmSparse"
##        features
## docs    creatie creatie creatie
##   text1       1       1       1

然后你可以重新编译dfm来编译计数。

# this combines counts in featnames that are identical
dfm_compress(dfm1)
## Document-feature matrix of: 1 document, 1 feature (0% sparse).
## 1 x 1 sparse Matrix of class "dfmSparse"
##        features
## docs    creatie
##   text1       3

请注意,如果您使用 quanteda 的词干分析器,这一步可能是 dfm_wordstem():

dfm_wordstem(dfm1)
## Document-feature matrix of: 1 document, 1 feature (0% sparse).
## 1 x 1 sparse Matrix of class "dfmSparse"
##        features
## docs    creati
##   text1      3