2015-10-13 44 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