【问题标题】:How to maintain ngrams in a quanteda dfm?如何在 quanteda dfm 中维护 ngram?
【发布时间】:2020-08-05 20:51:58
【问题描述】:

我正在使用 quanteda 从标记对象创建文档特征矩阵 (dfm)。我的令牌对象包含许多 ngram(例如:“united_states”)。当我使用 dfm() 函数创建 dfm 时,我的 ngram 被下划线分割(“united_states”被分割成“united”“states”)。如何在维护 ngram 的同时创建 dfm?

这是我的过程:

my_tokens <- tokens(my_corpus, remove_symbols=TRUE, remove_punct = TRUE, remove_numbers = TRUE)
my_tokens <- tokens_compound(pattern=phrase(my_ngrams))
my_dfm <- dfm(my_tokens, stem= FALSE, tolower=TRUE)

我在 my_tokens 中看到“united_states”,但在 dfm 中它变成了“united”和“states”作为单独的标记。

感谢您提供的任何帮助!

【问题讨论】:

    标签: r n-gram quanteda


    【解决方案1】:

    尚不清楚您使用的是哪个版本的 quanteda,但基本上这应该可以工作,因为默认标记器(来自 tokens())不会拆分包含内部 _ 的单词。

    演示:

    library("quanteda")
    ## Package version: 2.1.1
    
    # tokens() will not separate _ words
    tokens("united_states")
    ## Tokens consisting of 1 document.
    ## text1 :
    ## [1] "united_states"
    

    以下是短语“United States”的可重现示例:

    my_corpus <- tail(data_corpus_inaugural, 3)
    
    # show that the phrase exists
    head(kwic(my_corpus, phrase("united states"), window = 2))
    ##                                                                  
    ##  [2009-Obama, 2685:2686]   bless the | United States | of America
    ##      [2013-Obama, 13:14]      of the | United States | Congress, 
    ##  [2013-Obama, 2313:2314] bless these | United States | of America
    ##    [2017-Trump, 347:348]       , the | United States | of America
    ##  [2017-Trump, 1143:1144]      to the | United States | of America
    
    my_tokens <- tokens(my_corpus,
      remove_symbols = TRUE,
      remove_punct = TRUE, remove_numbers = TRUE
    )
    my_tokens <- tokens_compound(my_tokens, pattern = phrase("united states"))
    my_dfm <- dfm(my_tokens, stem = FALSE, tolower = TRUE)
    
    dfm_select(my_dfm, "*_*")
    ## Document-feature matrix of: 3 documents, 1 feature (0.0% sparse) and 4 docvars.
    ##             features
    ## docs         united_states
    ##   2009-Obama             1
    ##   2013-Obama             2
    ##   2017-Trump             2
    

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-09
      • 1970-01-01
      相关资源
      最近更新 更多