在 tm 文本挖掘 R 包的源代码中,在文件中变换R,有removePunctuation()
函数,当前定义为:
function(x, preserve_intra_word_dashes = FALSE)
{
if (!preserve_intra_word_dashes)
gsub("[[:punct:]]+", "", x)
else {
# Assume there are no ASCII 1 characters.
x <- gsub("(\\w)-(\\w)", "\\1\1\\2", x)
x <- gsub("[[:punct:]]+", "", x)
gsub("\1", "-", x, fixed = TRUE)
}
}
我需要解析和挖掘科学会议的一些摘要(从他们的网站上以 UTF-8 格式获取)。摘要包含一些需要删除的 unicode 字符,特别是在单词边界处。有常见的 ASCII 标点字符,但也有一些 Unicode 破折号、Unicode 引号、数学符号...
文本中还有 URL,还有需要保留词内标点符号的标点符号。 tm内置的removePunctuation()
功能太激进了。
所以我需要定制removePunctuation()
功能根据我的要求进行删除。
我的自定义 Unicode 函数现在看起来像这样,但它没有按预期工作。我很少使用 R,因此在 R 中完成工作需要一些时间,即使对于最简单的任务也是如此。
我的功能:
corpus <- tm_map(corpus, rmPunc = function(x){
# lookbehinds
# need to be careful to specify fixed-width conditions
# so that it can be used in lookbehind
x <- gsub('(.*?)(?<=^[[:punct:]’“”:±</>]{5})([[:alnum:]])'," \\2", x, perl=TRUE) ;
x <- gsub('(.*?)(?<=^[[:punct:]’“”:±</>]{4})([[:alnum:]])'," \\2", x, perl=TRUE) ;
x <- gsub('(.*?)(?<=^[[:punct:]’“”:±</>]{3})([[:alnum:]])'," \\2", x, perl=TRUE) ;
x <- gsub('(.*?)(?<=^[[:punct:]’“”:±</>]{2})([[:alnum:]])'," \\2", x, perl=TRUE) ;
x <- gsub('(.*?)(?<=^[[:punct:]’“”:±</>])([[:alnum:]])'," \\2", x, perl=TRUE) ;
# lookaheads (can use variable-width conditions)
x <- gsub('(.*?)(?=[[:alnum:]])([[:punct:]’“”:±]+)$',"\1 ", x, perl=TRUE) ;
# remove all strings that consist *only* of punct chars
gsub('^[[:punct:]’“”:±</>]+$',"", x, perl=TRUE) ;
}
它没有按预期工作。我认为,它根本没有任何作用。
标点符号仍在术语文档矩阵内,请参阅:
head(Terms(tdm), n=30)
[1] "<></>" "---"
[3] "--," ":</>"
[5] ":()" "/)."
[7] "/++" "/++,"
[9] "..," "..."
[11] "...," "..)"
[13] "“”," "(|)"
[15] "(/)" "(.."
[17] "(..," "()=(|=)."
[19] "()," "()."
[21] "(&)" "++,"
[23] "(0°" "0.001),"
[25] "0.003" "=0.005)"
[27] "0.006" "=0.007)"
[29] "000km" "0.01)"
...
所以我的问题是:
- 为什么对我的 function(){} 的调用没有达到预期的效果?我的怎么可以
功能有待改进吗?
- Unicode 正则表达式模式类是否如 if
\P{ASCII}
or \P{PUNCT}
R 的 perl 兼容正则支持
表达式?我认为他们不是(默认情况下)PCRE::“尽管支持最重要的属性,但仅对 \p 的各种 Unicode 属性的支持是不完整的。”