【发布时间】: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