【问题标题】:Quanteda R: How to remove numbers or symbols "from"/"in" a token?Quanteda R:如何从令牌“/”中删除数字或符号?
【发布时间】:2019-06-03 17:39:13
【问题描述】:

我对 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)。

我以为我删除了所有的符号和数字。为什么我仍然得到它们?

我很乐意得到一些帮助。

谢谢!!!

【问题讨论】:

  • 如果您查看tokens 的帮助,它会说,例如remove_numbers 将删除仅由数字组成的标记(单词),而不是与其他字符一起出现的数字。如果您需要的话,最好使用 stringr 包之类的东西从数据中取出这些数字和其他字符。

标签: r quanteda


【解决方案1】:

对于真正精细的控制,您需要通过模式替换自己处理文本。使用 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"

你的目标是什么,我(部分)猜测。

【讨论】:

  • 是否可以在 tokens 类的对象上执行您建议的完全相同的操作?例如,如果我执行quanta::tokens_remove(tokens(text), "[[:digit:]]),任何包含数字的标记都将被完全删除。这里是否有一种解决方法来避免在字符向量上循环并直接利用 quanteda 对象?
  • 您应该将此作为一个新问题提出并提供更多详细信息,但简而言之,您可以使用 tokens(x, remove_numbers = TRUE) 从令牌中删除数字。
猜你喜欢
  • 2019-03-30
  • 1970-01-01
  • 2016-06-18
  • 2013-07-19
  • 1970-01-01
  • 1970-01-01
  • 2014-01-05
  • 1970-01-01
  • 2022-11-30
相关资源
最近更新 更多