2016-11-20 100 views
2

我正在尝试从字符串创建dfm的单词。当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 /解d/F”,我想捕捉的字母 “/”, “ - ” 太
  2. 为什么 “”功能作为一个rowsum。我怎样才能保持它作为个人功能?
+0

Like'tokens < - tokenize(x,what =“character”); mat < - dfm(tokens,dictionary = dict,valuetype =“fixed”)'?在正则表达式(“正则表达式”)中,“。”代表任何字符。 – lukeA

+0

谢谢。这正是我所期待的。 – SuperSatya

回答

0

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

我们首先看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 

现在/-正在计数。 .'仍然作为功能存在,因为它们是字典键,但每个文档都有一个零计数。

+0

谢谢。我已经用'valuetype =“fixed”'参数修正了它,而没有removPunct。我想这不重要,因为它无论如何都捕捉到所有的标点符号。 – SuperSatya