我有兴趣替换 a 中的所有单词tm
根据由两列数据框组成的字典的语料库对象,其中第一列是要匹配的单词,第二列是替换单词。
我被困住了translate
功能。我看见这个答案但我无法将其转换为要传递给的函数tm_map
.
请考虑以下 MWE
library(tm)
docs <- c("first text", "second text")
corp <- Corpus(VectorSource(docs))
dictionary <- data.frame(word = c('first', 'second', 'text'),
translation = c('primo', 'secondo', 'testo'))
translate <- function(text, dictionary) {
# Would like to replace each word of text with corresponding word in dictionary
}
corp_translated <- tm_map (corp, translate)
inspect(corp_translated)
# Expected result
# A corpus with 2 text documents
#
# The metadata consists of 2 tag-value pairs and a data frame
# Available tags are:
# create_date creator
# Available variables in the data frame are:
# MetaID
# [[1]]
# primo testo
# [[2]]
# secondo testo
我会建议not用一个data.frame
对于字典来说,因为基本对象R
,一个向量,默认是一个字典。
dict <- c('primo', 'secondo', 'testo')
names(dict) <- c('first', 'second', 'text')
Then to "tanslate"
x
, where x
可能"second"
,您只需使用:
dict[[x]]
您甚至不需要包装函数。
如果您想向相反方向平移,请使用
name(dict)[names(dict) %in% x]
或者你可以翻一下字典
dict.flip <- names(dict)
names(dict.flip) <- dict
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)