【问题标题】:How to apply a custom function to a quanteda corpus如何将自定义函数应用于 quanteda 语料库
【发布时间】:2017-08-31 00:05:30
【问题描述】:

我正在尝试将脚本从使用 tm 迁移到 quanteda。阅读 quanteda 文档,有一种关于“下游”应用更改以使原始语料库保持不变的理念。好的。

我之前编写了一个脚本来查找我们的 tm 语料库中的拼写错误,并得到了我们团队的支持来创建手动查找。所以,我有一个包含 2 列的 csv 文件,第一列是拼写错误的术语,第二列是该术语的正确版本。

我之前使用 tm 包是这样做的:

# Write a custom function to pass to tm_map
# "Spellingdoc" is the 2 column csv
library(stringr)
library(stringi)
library(tm)
stringi_spelling_update <- content_transformer(function(x, lut = spellingdoc) stri_replace_all_regex(str = x, pattern = paste0("\\b", lut[,1], "\\b"), replacement = lut[,2], vectorize_all = FALSE))

然后在我的 tm 语料库转换中,我这样做了:

mycorpus <- tm_map(mycorpus, function(i) stringi_spelling_update(i, spellingdoc))

将此自定义函数应用于我的 quanteda 语料库的等效方法是什么?

【问题讨论】:

    标签: r text-mining quanteda


    【解决方案1】:

    无法从您的示例中知道这是否可行,这会遗漏一些部分,但通常:

    如果您想访问 quanteda 语料库中的文本,您可以使用texts(),并替换这些文本,texts()&lt;-

    所以在你的情况下,假设 mycorpus 是一个 tm 语料库,你可以这样做:

    library("quanteda")
    stringi_spelling_update2 <- function(x, lut = spellingdoc) {
        stringi::stri_replace_all_regex(str = x, 
                                        pattern = paste0("\\b", lut[,1], "\\b"), 
                                        replacement = lut[,2], 
                                        vectorize_all = FALSE)
    }
    
    myquantedacorpus <- corpus(mycorpus)
    texts(mycorpus) <- stringi_spelling_update2(texts(mycorpus), spellingdoc)
    

    【讨论】:

    • 嗨@Ken,实际上 mycorpus 是一个量子语料库。我最近才了解这个包。我想你的第二句话就是我要找的吗?但是,对于这个特殊问题,我注意到您为 dfm() 提供的字典功能,所以我改用它,但很高兴知道如果我需要对每个文档应用自定义函数,我会去texts(mycorpus) &lt;- myCustomFunction(myCorpus))(尽管我应该避免这种情况如果坚持不改变语料库的 quanteda 哲学)
    • 如果语料库中包含您从不感兴趣的拼写错误(例如产品OCR 错误)。我们要阻止的是人们应用词干分析器或从语料库本身中删除停用词。
    【解决方案2】:

    我想我在here 上找到了间接答案。

    texts(myCorpus) <- myFunction(myCorpus)
    

    【讨论】:

      猜你喜欢
      • 2018-08-09
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多