使用r根据模式列表中的精确匹配拆分文本

时间:2019-02-20 20:41:46

标签: r regex

我有文字和图案。

text <- "It is only a very poor quality car that can give big problems with automatic gearbox" 
patterns <- c("very poor","big problems")

分割文本

unlist(strsplit(text, "(\\s+)|(?!')(?=[[:punct:]])", perl = TRUE))

输出:

[1] "It"        "is"        "only"      "a"         "very"      "poor"      "quality"   "car"       "that"      "can"      
[11] "give"      "big"       "problems"  "with"      "automatic" "gearbox"

我需要的是匹配句子中的模式列表,而不是匹配“非常”,“较差”,与“大问题”一样变得“非常较差”。

样本输出:

[1] "It"     "is"     "only"    "a"    "very poor"   "quality"   "car"  "that"   "can"      
[10] "give"   "big problems"  "with"   "automatic"   "gearbox"

我应该怎么做?

1 个答案:

答案 0 :(得分:2)

这是一种方法:

library(stringr)
text <- "It is only a very poor quality car that can give big problems with automatic gearbox" 
patterns <- c("very poor","big problems")
patterns_ns <- setNames(str_replace_all(patterns, " ", "&&"), patterns)
text_ns <- str_replace_all(text, patterns_ns)
text_split <- str_replace_all(unlist(str_split(text_ns, "\\s")), "&&", " ")
text_split

我假设"&&"是一个实际上没有出现在源文本中的字符串,并且您想在空白处分割。

相关问题