【问题标题】:Output text with both unigrams and bigrams in R在 R 中输出包含一元和二元的文本
【发布时间】:2020-12-11 04:17:48
【问题描述】:

我试图弄清楚如何在 R 中的文本中识别一元和二元,然后根据阈值将两者保留在最终输出中。我已经用 gensim 的 Phraser 模型在 Python 中完成了这项工作,但还没有弄清楚如何在 R 中完成。

例如:

strings <- data.frame(text = 'This is a great movie from yesterday', 'I went to the movies', 'Great movie time at the theater', 'I went to the theater yesterday')
#Pseudocode below
bigs <- tokenize_uni_bi(strings, n = 1:2, threshold = 2)
print(bigs)
[['this', 'great_movie', 'yesterday'], ['went', 'movies'], ['great_movie', 'theater'], ['went', 'theater', 'yesterday']]

谢谢!

【问题讨论】:

    标签: r nlp n-gram


    【解决方案1】:

    您可以为此使用 quanteda 框架:

    library(quanteda)
    # tokenize, tolower, remove stopwords and create ngrams
    my_toks <- tokens(strings$text) 
    my_toks <- tokens_tolower(my_toks)
    my_toks <- tokens_remove(my_toks, stopwords("english"))
    bigs <- tokens_ngrams(my_toks, n = 1:2)
    
    # turn into document feature matrix and filter on minimum frequency of 2 and more
    my_dfm <- dfm(bigs)
    dfm_trim(my_dfm, min_termfreq = 2)
    
    Document-feature matrix of: 4 documents, 6 features (50.0% sparse).
           features
    docs    great movie yesterday great_movie went theater
      text1     1     1         1           1    0       0
      text2     0     0         0           0    1       0
      text3     1     1         0           1    0       1
      text4     0     0         1           0    1       1
    
    # use convert function to turn this into a data.frame
    

    或者,您可以使用 tidytext 包、tm、标记器等。这完全取决于您期望的输出。

    使用 tidytext / dplyr 的示例如下所示:

    library(tidytext)
    library(dplyr)
    strings %>% 
      unnest_ngrams(bigs, text, n = 2, n_min = 1, ngram_delim = "_", stopwords = stopwords::stopwords()) %>% 
      count(bigs) %>% 
      filter(n >= 2)
    
             bigs n
    1       great 2
    2 great_movie 2
    3       movie 2
    4     theater 2
    5        went 2
    6   yesterday 2
    

    quanteda 和 tidytext 都有很多可用的在线帮助。请参阅 cran 上的两个包的小插曲。

    【讨论】:

    • 谢谢@phiver!第二个答案正是我正在寻找的 - 应该在 tidytext 文档中更加努力。
    • 只是对这个非常好的答案的一个脚注:quanteda 支持/重新导出%&gt;% 以及dplyr 样式的链是可能的。
    猜你喜欢
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 2011-07-05
    • 2019-09-02
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多