2

在使用 R 进行文本挖掘时,在对文本数据进行再处理后,我们需要创建一个文档术语矩阵以进行进一步探索。但是和中文类似,英文也有一些特定的阶段,比如“语义距离”、“机器学习”,如果你把它们分割成单词,它就有完全不同的含义,我想知道如何匹配预定义的字典值由空格分隔的术语组成,例如包含“语义距离”、“机器学习”。如果一个文档是“我们可以使用机器学习的方法来计算词的语义距离”,当将该文档应用于字典[“语义距离”,“机器学习”]时,它将返回一个1x2矩阵:[语义距离,1 ;机器学习,1]

4

1 回答 1

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"            "."    

最后,我们可以构造文档特征矩阵,使用默认的“glob”模式匹配包含下划线字符的所有短语:

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)

于 2016-04-20T04:22:27.553 回答