【问题标题】:creating a dfm of words with letters用字母创建单词的dfm
【发布时间】:2016-11-20 02:10:50
【问题描述】:

我正在尝试从字符串创建一个 dfm 字母。当 dfm 无法选择可以为“/”“-”“”等标点符号创建功能时,我遇到了问题。或'。

require(quanteda)
dict = c('a','b','c','d','e','f','/',".",'-',"'")
dict <- quanteda::dictionary(sapply(dict, list))

x<-c("cab","baa", "a/de-d/f","ad")
x<-sapply(x, function(x) strsplit(x,"")[[1]])
x<-sapply(x, function(x) paste(x, collapse = " "))

mat <- dfm(x, dictionary = dict, valuetype = "regex")
mat <- as.matrix(mat)
mat
  1. 对于“a/de-d/f”,我也想捕获字母“/”“-”
  2. 为什么是“。”作为 rowsum 的特征。如何将其保留为单独的功能?

【问题讨论】:

  • 喜欢tokens &lt;- tokenize(x, what = "character"); mat &lt;- dfm(tokens, dictionary = dict, valuetype = "fixed")?在正则表达式(“regex”)中,. 代表任何字符。
  • 谢谢。这正是我想要的。

标签: r sapply quanteda dfm


【解决方案1】:

问题(正如@lukeA 在评论中指出的那样)是您的valuetype 使用了错误的模式匹配。您正在使用正则表达式,其中 . 代表任何字符,因此这里得到一个总数(您称之为行和)。

我们先来看x,它会在空格上被dfm()标记化,这样每个字符就变成了一个标记。

x
#        cab               baa          a/de-d/f                ad 
#    "c a b"           "b a a" "a / d e - d / f"             "a d" 

首先要回答 (2),您将通过“正则表达式”匹配获得以下内容:

dfm(x, dictionary = dict, valuetype = "regex", verbose = FALSE)
## Document-feature matrix of: 4 documents, 10 features.
## 4 x 10 sparse Matrix of class "dfmSparse"
##           features
## docs       a b c d e f / . - '
##   cab      1 1 1 0 0 0 0 3 0 0
##   baa      2 1 0 0 0 0 0 3 0 0
##   a/de-d/f 1 0 0 2 1 1 0 5 0 0
##   ad       1 0 0 1 0 0 0 2 0 0

这很接近,但没有回答 (1)。要解决这个问题,您需要通过 dfm() 更改默认标记化行为,以便它不会删除标点符号。

dfm(x, dictionary = dict, valuetype = "fixed", removePunct = FALSE, verbose = FALSE)
## Document-feature matrix of: 4 documents, 10 features.
## 4 x 10 sparse Matrix of class "dfmSparse"
##           features
## docs       a b c d e f / . - '
##   cab      1 1 1 0 0 0 0 0 0 0
##   baa      2 1 0 0 0 0 0 0 0 0
##   a/de-d/f 1 0 0 2 1 1 2 0 1 0
##   ad       1 0 0 1 0 0 0 0 0 0

现在正在计算/-.' 仍然作为特征存在,因为它们是字典键,但每个文档的计数为零。

【讨论】:

  • 谢谢。我已经用valuetype = "fixed" 参数和没有removPunct 修复了它。我想这无关紧要,因为无论如何它都会抓住所有标点符号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-10
  • 2022-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多