如何使用 Regex 去除标点符号而不污染像中文这样的 UTF-8 或 UTF-16 编码文本?

How to use Regex to strip punctuation without tainting UTF-8 or UTF-16 encoded text like chinese?

如何在不弄乱 R 中的 UTF-8 原始字符(特别是中文)的情况下从 ASCII 和 UTF-8 编码的字符串中去除标点符号。

text <- "Longchamp Le Pliage 肩背包 (小)"
stri_replace_all_regex(text, '\p{P}', '')

结果:

Longchamp Le Pliage ��背�� 小

但期望的结果应该是:

Longchamp Le Pliage 肩背包 小

我希望删除所有 CJK 符号和标点符号以及 ASCII 标点符号。

@akrun,sessionInfo()如下

locale:
[1] LC_COLLATE=English_Singapore.1252  LC_CTYPE=English_Singapore.1252    LC_MONETARY=English_Singapore.1252
[4] LC_NUMERIC=C                       LC_TIME=English_Singapore.1252    

汉字 (hanzi) 的显示因平台和 IDE 而异(有关 R 处理非 ASCII 字符的详细信息,请参阅 this answer)。在我看来 stri_replace_all_regex 正在做你想做的事,但有些汉字显示错误(即使它们的底层代码点是正确的)。试试这个:

library(stringi)
my_text <- "Longchamp Le Pliage 肩背包 (小)"
plot(0,0)
text(0, 0, my_text, pos=3)

如果您可以让文本显示在绘图上,则说明字符串在底层已正确编码,问题在于它在 R 终端中的显示方式。如果不是,请检查 Encoding(my_text) 并考虑在进一步的文本处理之前使用 enc2utf8。如果绘图有效,请尝试:

no_punct <- stri_replace_all_regex(my_text, "\p{P}", "")
text(0, 0, no_punct, pos=1)

查看 stri_replace_all_regex 的结果是否确实符合您的预期。