2016-05-12 105 views
2

您好:我使用tm软件包进行一些文本分析,并且我需要用向量中的配对替换项更换。所以模式/替换字典看起来像这样。使用mapply来替换矢量中的模式替换tm中的矢量

#pattern -replacement dictionary 
df<-data.frame(replace=c('crude', 'oil', 'price'), with=c('xcrude', 'xoil', 'xprice')) 
#load tm 
library(tm) 
#load crude 
data('crude') 

我尝试这样做,收到错误

tm_map(crude, mapply, gsub, df$replace, df$with) 

Warning message: 
In mclapply(content(x), FUN, ...) : 
all scheduled cores encountered errors in user code 
+0

您是否必须使用'tm'来做到这一点? – Sotos

+0

基本上可以。我很确定我可以在它之外做到这一点,但我想知道如何在tm中做到这一点。 – spindoctor

回答

2

在此基础上answer你可以使用stringi并绕到它content_transformer()保持胼结构:

corp <- tm_map(crude, content_transformer(
    function(x) { 
    stri_replace_all_fixed(x, df$replace, df$with, vectorize_all = FALSE) 
    }) 
) 

或者multigsubqdap

corp <- tm_map(crude, content_transformer(
    function(x) { 
    multigsub(df$replace, df$with, fixed = FALSE, x) 
    }) 
) 

其中给出:

> corp[[1]][1] 

“钻石三叶草公司说,\今天neffective它由\ n1.50 DLRS每桶下调了 合同xpricesxcrude xoil \。该减少带来其西德克萨斯州xprice \ n中间到 16.00 dlrs一桶,copany说。\ n“xprice今天减少是根据f阿灵\ n xoil产品xprices 和弱xcrude xoil市场,\”公司\ nspokeswoman说。\ n
钻石是在一条线上美国的最新xoil公司,\ nhave 切其合同,或张贴,xprices在过去两年 天\ nciting弱xoil市场。\ n路透社”

您可以再申请其他tm对所得语料库的功能:

> DocumentTermMatrix(corp) 
#<<DocumentTermMatrix (documents: 20, terms: 1269)>> 
#Non-/sparse entries: 2262/23118 
#Sparsity   : 91% 
#Maximal term length: 17 
#Weighting   : term frequency (tf) 
+1

如果要替换的术语字典实际上是正则表达式,那么我会使用: stri_replace_all_regex – spindoctor

+0

@spindoctor当然,这应该工作得很好。 –

+1

所以,这只是部分工作。当你检查返回的结构时,它是一个列表,而不是一个语料库。 #检查结构 STR(公司) STR(原油) #检查类本是同 类(公司) 类(原油) 我认为这是显著因为现在基本功能类似于DocumentTermMatrix现在不再工作> #DTM DocumentTermMatrix(corp) DocumentTermMatrix(粗) – spindoctor