【问题标题】:Removing hyphens in http but preserving hyphenated words in corpus删除http中的连字符但保留语料库中的连字符
【发布时间】:2018-10-05 11:15:01
【问题描述】:

我正在尝试修改一个能够 1)删除 http 中的连字符(出现在语料库中)但同时 2)保留出现在有意义的连字符表达式中的连字符(例如,耗时、成本-禁止等)。 实际上几个月前我在另一个question thread 上问过类似的问题,代码如下所示:

# load stringr to use str_replace_all
require(stringr)

clean.text = function(x)
{
  # remove rt
  x = gsub("rt ", "", x)
  # remove at
  x = gsub("@\\w+", "", x)
  x = gsub("[[:punct:]]", "", x)
  x = gsub("[[:digit:]]", "", x)
  # remove http
  x = gsub("http\\w+", "", x)
  x = gsub("[ |\t]{2,}", "", x)
  x = gsub("^ ", "", x)
  x = gsub(" $", "", x)
  x = str_replace_all(x, "[^[:alnum:][:space:]'-]", " ")
  #return(x)
}

# example
my_text <- "accident-prone"
new_text <- clean.text(text)
new_text
[1] "accidentprone"

但没有得到满意的答案,我随后将注意力转移到其他项目上,直到恢复工作。看来代码块最后一行中的"[^[:alnum:][:space:]'-]" 也是从语料库的非http 部分中删除- 的罪魁祸首。

我不知道如何实现我们想要的输出,如果有人能就此提供他们的见解,我们将不胜感激。

【问题讨论】:

  • 尝试用 gsub("\\b-\\b(*SKIP)(*F)|[^[:alnum:][:space:]'-]", " ", x, perl=TRUE) 替换 str_replace_all(x, "[^[:alnum:][:space:]'-]", " ") 或 - 保持模式 Unicode 感知 - gsub("(*UCP)\\b-\\b(*SKIP)(*F)|[^\\w\\s'-]|_", " ", x, perl=TRUE)
  • 它仍然给出相同的结果。
  • 好的,将x = gsub("[[:punct:]]", "", x) 替换为x = gsub("(?!-)[[:punct:]]", "", x, perl=TRUE)。请注意,您仍然可以通过将str_replace 行替换为x = gsub("[^[:alnum:][:space:]'-]", " ", x) 来摆脱stringr

标签: r regex stemming punctuation hyphenation


【解决方案1】:

真正的罪魁祸首是 [[:punct:]] 删除模式,因为它匹配字符串中任何位置的 -

你可以使用

clean.text <- function(x)
{
  # remove rt
  x <- gsub("rt\\s", "", x)
  # remove at
  x <- gsub("@\\w+", "", x)
  x <- gsub("\\b-\\b(*SKIP)(*F)|[[:punct:]]", "", x, perl=TRUE)
  x <- gsub("[[:digit:]]+", "", x)
  # remove http
  x <- gsub("http\\w+", "", x)
  x <- gsub("\\h{2,}", "", x, perl=TRUE)
  x <- trimws(x)
  x <- gsub("[^[:alnum:][:space:]'-]", " ", x)
  return(x)
}

那么,

my_text <- "  accident-prone  http://www.some.com  rt "
new_text <- clean.text(my_text)
new_text 
## => [1] "accident-prone"

请参阅R demo

注意:

  • x = gsub("^ ", "", x)x = gsub(" $", "", x) 可以替换为 trimws(x)
  • gsub("\\b-\\b(*SKIP)(*F)|[[:punct:]]", "", x, perl=TRUE) 删除单词字符之间的任何标点符号但连字符(您可以在 (*SKIP)(*F) 之前的部分中进一步调整)
  • gsub("[^[:alnum:][:space:]'-]", " ", x)str_replace_all(x, "[^[:alnum:][:space:]'-]", " ") 的基本 R 等效项。
  • gsub("\\h{2,}", "", x, perl=TRUE) 删除任何 2 个或更多水平空格。如果 "[ |\t]{2,}" 是要匹配任意 2 个或更多空格,请在此处使用 \\s 而不是 \\h

【讨论】:

  • 非常感谢您提供如此详细的解释!我将在gsub 上阅读更多内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
  • 1970-01-01
  • 2021-03-26
  • 2018-06-24
  • 1970-01-01
  • 2018-12-28
相关资源
最近更新 更多