【问题标题】:insert commas in text string after certain words in r在 r 中的某些单词之后在文本字符串中插入逗号
【发布时间】:2019-01-07 17:01:55
【问题描述】:

这里是示例数据:

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"))

reprex package (v0.2.1) 于 2019-01-07 创建

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

problem not fixed.

我想把它转换成

problem, not fixed.

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

我查看了stringr 包,但不知道如何实现。

最好的,

【问题讨论】:

  • @MrFlick 我使用 reprex 示例进行了编辑

标签: r regex nlp stringr


【解决方案1】:

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"

【讨论】:

  • 这病了!!今天试一试
【解决方案2】:

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

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

【讨论】:

  • 我编辑了问题,但您的解决方案看起来不错。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多