2016-04-20 35 views
1

在使用R进行文本挖掘时,在重新处理文本数据之后,我们需要创建文档项矩阵以供进一步探索。但是与中国人相似,英语也有一些特定的阶段,比如“语义距离”,“机器学习”,如果将它们分成单词,它们有完全不同的含义,我想知道如何匹配预定义的词典值由空白分隔的项组成,例如包含“语义距离”,“机器学习”。如果一个文档是“我们可以使用机器学习方法来计算词语的语义距离”,那么当将这个文档应用于词典[“语义距离”,“机器学习”]时,它会返回一个1x2矩阵:[语义距离,1 ;机器学习,1]R构造文档术语矩阵如何匹配其值由空格分隔的短语组成的词典

回答

2

虽然它需要为每个短语构造一个字典,然后预处理文本以将短语转换为标记,但可以用quanteda做到这一点。要成为“标记”,短语需要加上除空白之外的东西 - 这里是“_”字符。

以下是一些示例文本,包括OP中的短语。我为示例添加了两个额外的文本 - 下面,文档特征矩阵的第一行生成请求的答案。

txt <- c("We could use machine learning method to calculate the words semantic distance.", 
     "Machine learning is the best sort of learning.", 
     "The distance between semantic distance and machine learning is machine driven.") 

词组令牌的电流签名要求phrases参数是字典或搭配对象。在这里,我们将使它的字典:

mydict <- dictionary(list(machine_learning = "machine learning", 
          semantic_distance = "semantic distance")) 

然后我们预处理到词典的短语转换成自己的钥匙文:

toks <- tokens(txt) %>% 
    tokens_compound(mydict) 
toks 
# tokens from 3 documents. 
# text1 : 
# [1] "We"    "could"    "use"    "machine_learning" 
# [5] "method"   "to"    "calculate"   "the"    
# [9] "words"    "semantic_distance" "."     
# 
# text2 : 
# [1] "Machine_learning" "is"    "the"    "best"    
# [5] "sort"    "of"    "learning"   "."    
# 
# text3 : 
# [1] "The"    "distance"   "between"   "semantic_distance" 
# [5] "and"    "machine_learning" "is"    "machine"   
# [9] "driven"   "."  

最后,我们可以构造文档特征矩阵,保持使用默认的“水珠”模式匹配用于包括下划线字符的任何特征都短语:

mydfm <- dfm(toks, select = "*_*") 
mydfm 
## Document-feature matrix of: 3 documents, 2 features. 
## 3 x 2 sparse Matrix of class "dfm" 
##  features 
## docs machine_learning semantic_distance 
## text1    1     1 
## text2    1     0 
## text3    1     1 

(回答更新的> = v0.9.9)

+1

它的工作原理,谢谢 –

+0

但是,如果字典有一个正则表达式模式的键,'phrasetotoken'不起作用 –

+0

这是正确的,不幸的是。但是,当我添加对多字词典值的支持时,它将起作用。 –

相关问题