【问题标题】:ngrams analysis in tidytext in RR中tidytext中的ngrams分析
【发布时间】:2020-02-14 05:26:57
【问题描述】:

我正在尝试在 tidytext 中进行 ngram 分析,我有一个包含 770 个演讲的语料库。但是 tidytext 中的函数 unnest_tokens 将数据框作为输入。当我检查示例(简奥斯汀书籍)时,书中的每一行都作为行存储在数据框中。我无法将语料库转换为数据帧,既不能一次用于一个语音,也不能一次用于所有语料库。

我可以使用我的语料库上的非嵌套标记对 tidytext 运行 ngrams(n=2,3 等)分析的方式是什么。有人可以建议吗?

谢谢

【问题讨论】:

  • 请创建一个reproducible example 和预期的输出。但对我来说,这听起来好像你只需要使用 quanteda 而不是 tidytext。

标签: r tidytext


【解决方案1】:

您可以为此使用库 ngram & tm。您可以将“myCorpus”替换为您创建的语料库。

library(tm)
library(ngarm)
myCorpus<-c("Hi How are you","Hello World","I love Stackoverflow","Good Bye All")
ng <- ngram (myCorpus , n =2)
get.phrasetable (ng)

如果您想对语料库进行标记并将其转换为数据框,请使用以下代码。

 tokenizedCorpus <- lapply(myCorpus, scan_tokenizer)
 mydata <- data.frame(text = sapply(tokenizedCorpus, paste, collapse = " "),stringsAsFactors = FALSE)

【讨论】:

  • 嗨,我知道同样的情况,但这在我的情况下没有用,因为我不想为整个语料库做这件事,因为我提到我有 770 次演讲,我想工作分别在每一个上,我也想使用 tidytext,因为我想在 ngrams 上进一步使用相同的 otehr 功能,所以我需要关于 ngrams 的 tidytxt 功能的帮助
  • 如果你想单独做,你可以尝试使用for循环来迭代,为每个语音创建一个单独的语料库和ngram。我将研究在 tidy text 包中找到 ngrams 的解决方案。
【解决方案2】:

你说你有一个包含 770 个演讲的“语料库”。你的意思是你有一个字符向量?如果是这样,您可以通过以下方式标记您的文本:

library(tidyverse)
library(tidytext)

speech_vec <- c("I am giving a speech!",
                "My second speech is even better.",
                "Unfortunately, this speech is terrible!",
                "For my final speech, I will wow you all.")

speech_df <- tibble(text = speech_vec) %>%
  mutate(speech = row_number())

tidy_speeches <- speech_df %>%
  unnest_tokens(bigram, text, token = "ngrams", n = 2)

tidy_speeches
#> # A tibble: 21 x 2
#>    speech bigram            
#>     <int> <chr>             
#>  1      1 i am              
#>  2      1 am giving         
#>  3      1 giving a          
#>  4      1 a speech          
#>  5      2 my second         
#>  6      2 second speech     
#>  7      2 speech is         
#>  8      2 is even           
#>  9      2 even better       
#> 10      3 unfortunately this
#> # … with 11 more rows

reprex package (v0.3.0) 于 2020 年 2 月 15 日创建

如果相反,你的意思是你有一个来自 tm 包的DocumentTermMatrixcheck out this chapter for details 关于如何转换成一个整洁的数据结构。

【讨论】:

  • 嗨,几天前我在查看链接时发现了同样的情况。无论如何,谢谢
猜你喜欢
  • 1970-01-01
  • 2020-08-04
  • 2017-01-06
  • 1970-01-01
  • 1970-01-01
  • 2018-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多