在文本字符串中在 R 中的某些单词之后插入逗号



下面是示例数据:

example_sentences <- data.frame(doc_id = c(1,2,3),
                                sentence_id = c(1,2,3),
                                sentence = c("problem not fixed","i like your service and would tell others","peope are nice however the product is rubbish"))
matching_df <- data.frame(x = c("not","and","however"))

创建于 2019-01-07 由 reprex 软件包 (v0.2.1)

我想在字符串中的某个word之前添加/插入逗号。 例如,如果我的字符串是:

problem not fixed.

我想将其转换为

problem, not fixed.

另一个matching_df包含要匹配的单词(这些是Coordinate conjunctions),因此如果在matching_df中找到x,则在detected word之前插入comma + space

我已经查看了stringr包,但不确定如何实现这一目标。

最好

我不知道

你说的数据框是什么样子的,但我在这里做了一个简单的数据框,其中包含一些短语:

df <- data.frame(strings = c("problems not fixed.","Help how are you"),stringsAsFactors = FALSE)

然后我做了一个单词向量,在后面加上一个逗号:

words <- c("problems","no","whereas","however","but")

然后我把短语的数据框通过一个简单的 for 循环,使用 gsub 用单词代替单词 + 逗号:

for (i in 1:length(df$strings)) {
    string <- df$strings[i]
    findWords <- intersect(unlist(strsplit(string," ")),words)
    if (!is.null(findWords)) {
        for (j in findWords) {
            df$strings[i] <- gsub(j,paste0(j,","),string)
        }
    }
}

输出:

 df
               strings
1 problems, not fixed.
2     Help how are you

gsubfn 包中的 gsubfn 函数将正则表达式作为第一个参数,将列表(或某些其他对象)作为第二个参数,其中列表的名称是要匹配的字符串,列表中的值是替换字符串。

library(gsubfn)
gsubfn("\w+", as.list(setNames(paste0(matching_df$x, ","), matching_df$x)), 
  format(example_sentences$sentence))

给:

[1] "problem not, fixed                            "
[2] "i like your service and, would tell others    "
[3] "peope are nice however, the product is rubbish"

最新更新