2015-10-13 64 views
1

此问题与我先前的问题有关。 Treat words separated by space in the same manner在字符串中查找单词时计算术语文档矩阵也

将它作为单独的发布,因为它可以帮助其他用户轻松找到它。

现在的问题是term document matrix的计算方式是tm包。我想稍微调整一下这个方法。

当前任何期限的文档矩阵都是通过在文档中查找单词'milky'作为单独的单词(而不是字符串)来创建的。例如,让我们假设2个文件

document 1: "this is a milky way galaxy" 
document 2: "this is a milkyway galaxy" 

由于每路电流算法工程(tm包)“天河”将得到第一个文档中而不是在第二份文件中发现,因为算法查找术语milky作为单独的词。但是,如果算法查找术语milky像函数grepl这样的字符串,它会在第二个文档中找到术语“乳白色”。

grepl('milky', 'this is a milkyway galaxy') 
TRUE 

是否有人可以帮助我建立一个术语文档矩阵满足我的要求(这是为了能够找到长期milky在这两个文件。请注意,我不想解决特定的词汇或milky,我想要一个通用的解决方案,我将在更大的范围内应用于处理所有这些情况)?即使解决方案没有使用tm包,也没关系。我只需要得到一个符合我的要求的期限文档矩阵。 最终,我希望能够获得一个词条文档矩阵,使其中的每个词条都应该在所讨论的文档的所有字符串内部被查找为字符串(而不仅仅是单词)(grepl类似于计算术语文档矩阵时的功能) 。

,我用它来获得长期文档矩阵当前的代码

doc1 <- "this is a document about milkyway" 
doc2 <- "milky way is huge" 

library(tm) 
tmp.text<-data.frame(rbind(doc1,doc2)) 
tmp.corpus<-Corpus(DataframeSource(tmp.text)) 
tmpDTM<-TermDocumentMatrix(tmp.corpus, control= list(tolower = T, removeNumbers = T, removePunctuation = TRUE,stopwords = TRUE,wordLengths = c(2, Inf))) 
tmp.df<-as.data.frame(as.matrix(tmpDTM)) 
tmp.df 

     1 2 
document 1 0 
huge  0 1 
milky 0 1 
milkyway 1 0 
way  0 1 
+0

在'milky'前后使用'\ b' – pcantalupo

+0

@pcantalupo我在哪里使用'/ b'?正如我已经解释的那样,问题并不仅仅是'乳白'。 '乳白色'就是一个例子。最终,我希望能够创建一个术语文档矩阵,该矩阵的计算方式应使每个术语在文档的字符串中查找。 – user3664020

+0

'grepl('\\ bmilky \\ b','这是银河系的星系')'会返回假 – pcantalupo

回答

0

我不知道TM很容易(或可能)来选择或群组功能基于正则表达式。但是文本包quanteda通过thesaurus参数确实可以在构造文档特征矩阵时根据字典对术语进行分组。

quanteda使用通用术语“功能”,因为在这里,你的类是包含短语乳白色方面,而不是原来的“条款”)。

valuetype参数可以是“水珠”格式(默认),正则表达式("regex")或原样("fixed")。下面我显示带有glob和正则表达式的版本。

require(quanteda) 
myDictGlob <- dictionary(list(containsMilky = c("milky*"))) 
myDictRegex <- dictionary(list(containsMilky = c("^milky"))) 

(plainDfm <- dfm(c(doc1, doc2))) 
## Creating a dfm from a character vector ... 
## ... lowercasing 
## ... tokenizing 
## ... indexing documents: 2 documents 
## ... indexing features: 9 feature types 
## ... created a 2 x 9 sparse dfm 
## ... complete. 
## Elapsed time: 0.008 seconds. 
## Document-feature matrix of: 2 documents, 9 features. 
## 2 x 9 sparse Matrix of class "dfmSparse" 
## features 
## docs this is a document about milkyway milky way huge 
## text1 1 1 1  1  1  1  0 0 0 
## text2 0 1 0  0  0  0  1 1 1 

dfm(c(doc1, doc2), thesaurus = myDictGlob, valuetype = "glob", verbose = FALSE) 
## Document-feature matrix of: 2 documents, 8 features. 
## 2 x 8 sparse Matrix of class "dfmSparse" 
##  this is a document about way huge CONTAINSMILKY 
## text1 1 1 1  1  1 0 0    1 
## text2 0 1 0  0  0 1 1    1 
dfm(c(doc1, doc2), thesaurus = myDictRegex, valuetype = "regex") 
## Document-feature matrix of: 2 documents, 8 features. 
## 2 x 8 sparse Matrix of class "dfmSparse" 
##  this is a document about way huge CONTAINSMILKY 
## text1 1 1 1  1  1 0 0    1 
## text2 0 1 0  0  0 1 1    1