【问题标题】:Replace words with stringi用字符串替换单词
【发布时间】:2016-01-29 19:49:25
【问题描述】:

我正在尝试使用 stringi 来替换使用 stri_replace 的某些单词,但是在替换单词的相似部分时遇到了问题。在下面的示例中,我正在修复三角形的拼写错误,但它似乎变得混乱,因为 'tri' 是 'trian' 的一部分,是 'triangle' 的一部分,它的输出就像 'trainglegle'。我对stri_replace 不是很熟悉,有什么我遗漏的论点吗?感谢您的帮助。

stri_replace_all_regex("The quick brown tri jumped over the lazy trian.",
      c("tri", "trian", "fox"), c("triangle",  "triangle", "bear"), 
         vectorize_all=FALSE)

## [1] "The quick brown trianglegle jumped over the lazy triangleglean."

【问题讨论】:

  • 请删除标题中的错误。这是您不理解正则表达式而不是错误。

标签: r nlp stringi


【解决方案1】:

您可能想要隔离单词,以便它们不同。 \\W 是非字符。你可以试试这样的:

stri_replace_all_regex("The quick brown tri jumped over the lazy trian.",
                   paste0(c("trian", "tri",  "fox"), "(\\W)"), 
                   paste0(c("triangle","triangle", "bear"),"$1"),
                   vectorize_all = FALSE)
[1] "The quick brown triangle jumped over the lazy triangle."

【讨论】:

  • 这很好用,但由于某种原因,当我尝试用“valueable”替换“val”时,它会选择“oval”这个词并将其变成“ovaluable”下面的代码:stri_replace_all_regex("快速的棕色椭圆跳过了懒惰的 trian。", paste0(c("val", "trian", "fox"), "(\\W)"), paste0(c("valueable","triangle", "bear"),"$1"), vectorize_all = FALSE) [1] "快速的棕色椭圆跳过了懒惰的三角形。"
  • 你只需要对开头的单词做同样的事情:stri_replace_all_regex("The quick brown oval jumped over the lazy trian.", paste0("(\\W)", c("val", "trian", "fox"), "(\\W)"), paste0("$1", c("valuable","triangle", "bear"),"$2"), vectorize_all = FALSE) 产生[1] "The quick brown oval jumped over the lazy triangle."
【解决方案2】:

如果您不希望完成部分匹配,则终止一些(甚至可能所有模式参数)用空格(并替换空格:

stri_replace_all_regex("The quick brown tri jumped over the lazy trian.",
  pattern=c("tri "), repl=c("triangle "), 
     vectorize_all=FALSE)

stri_replace_all_regex("The quick brown tri jumped over the lazy trian.",
       c("tri ", "trian", "fox "), c("triangle ",  "triangle", "bear "), 
          vectorize_all=TRUE)
[1] "The quick brown triangle jumped over the lazy trian."
[2] "The quick brown tri jumped over the lazy triangle."  
[3] "The quick brown tri jumped over the lazy trian."     

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 2015-07-03
    • 2014-01-08
    • 1970-01-01
    相关资源
    最近更新 更多