-1

嗨朋友们我正在尝试在文件列表中搜索特定的关键字(以 txt 给出)。我正在使用正则表达式来检测和替换文件中关键字的出现。下面是一个逗号分隔的关键字,我传递给它进行搜索。

library(stringi)
txt <- "automatically got activated,may be we download,network services,food quality is excellent"

例如“自动被激活”应该被搜索并替换为automatic_got_activated...“可能是我们下载”替换为“may_be_we_download”等等。

txt <- "automatically got activated,may be we download,network services,food quality is excellent"

for(i in 1:length(txt)) {
    start <- head(strsplit(txt, split=" ")[[i]], 1) #finding the first word of the keyword 
    n <- stri_stats_latex(txt[i])[4]        #number of words in the keyword

    o <- tolower(regmatches(text, regexpr(paste0(start,"(?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,",
        n-1,"}"),text,ignore.case=TRUE)))   #best match for keyword for the regex in the file 

    p <- which(!is.na(pmatch(txt, o)))      #exact match for the keywords
}
4

1 回答 1

1

我想这可能是你正在寻找的。

> txt <- "automatically got activated,may be we download,network services,food quality is excellent"

要搜索的句子组成向量:

> searchList <- c('This is a sentence that automatically got activated',
                  'may be we download some music tonight',
                  'I work in network services',
                  'food quality is excellent every time I go',
                  'New service entrance',
                  'full quantity is excellent')

完成这项工作的功能:

replace.keyword <- function(text, toSearch)
{
    kw <- unlist(strsplit(txt, ','))
    gs <- gsub('\\s', '_', kw)
    sapply(seq(kw), function(i){
      ul <- ifelse(grepl(kw[i], toSearch),
                   gsub(kw[i], gs[i], toSearch),
                   "")
      ul[nzchar(ul)]
    })
}

结果:

> replace.keyword(txt, searchList)
# [1] "This is a sentence that automatically_got_activated"
# [2] "may_be_we_download some music tonight"              
# [3] "I work in network_services"                         
# [4] "food_quality_is_excellent every time I go"   

请让我知道这对你有没有用。

于 2014-05-22T14:50:54.267 回答