r - Quanteda R:如何从令牌“/”中删除数字或符号?
问题描述
我对 quanteda R 中的语言预处理有疑问。我想根据一些文档生成一个文档特征矩阵。因此,我生成了一个语料库并运行以下代码。
data <- read.csv2("abstract.csv", stringsAsFactors = FALSE)
corpus<-corpus(data, docid_field = "docname", text_field = "documents")
dfm <- dfm(corpus, stem = TRUE, remove = stopwords('english'),
remove_punct = TRUE, remove_numbers = TRUE,
remove_symbols = TRUE, remove_hyphens = TRUE)
当我检查 dfm 时,我注意到一些标记 ( #ml, @attribut, _iq, 0.01ms
)。我宁愿拥有(ml, attribut, iq, ms
)。
我以为我删除了所有的符号和数字。为什么我仍然得到它们?
我很乐意得到一些帮助。
谢谢!!!
解决方案
对于真正精细的控制,您需要通过模式替换自己处理文本。使用stringi(或stringr),您可以轻松地替换符号或标点符号的 Unicode 类别。
考虑这个例子。
txt <- "one two, #ml @attribut _iq, 0.01ms."
quanteda::tokens(txt, remove_twitter = TRUE, remove_punct = TRUE)
## tokens from 1 document.
## text1 :
## [1] "one" "two" "ml" "attribut" "_iq" "0.01ms"
这是删除可能表示“Twitter”或其他社交媒体约定的特殊字符的简单方法。
对于更底层的控制:
# how to remove the leading _ (just to demonstrate)
stringi::stri_replace_all_regex(txt, "(\\b)_(\\w+)", "$1$2")
## [1] "one two, #ml @attribut iq, 0.01ms."
# remove all digits
(txt <- stringi::stri_replace_all_regex(txt, "\\d", ""))
## [1] "one two, #ml @attribut _iq, .ms."
# remove all punctuation and symbols
(txt <- stringi::stri_replace_all_regex(txt, "[\\p{p}\\p{S}]", ""))
## [1] "one two ml attribut iq ms"
quanteda::tokens(txt)
## tokens from 1 document.
## text1 :
## [1] "one" "two" "ml" "attribut" "iq" "ms"
这是你的目标,我(部分)猜测。