如何使用 tidytext 库在 R 中标记我的数据集?

How to tokenize my dataset in R using the tidytext library?

我一直在尝试关注 Julia Silge 的 Text Mining with R,但是,我无法使用 unnest_tokens 函数标记我的数据集。

这是我加载的包:

# Load
library(tm)
library(SnowballC)
library(wordcloud)
library(RColorBrewer)
library(corpus)
library(corpustools)
library(dplyr)
library(tidyverse)
library(tidytext)
library(tokenizers)
library(stringr)

这是我尝试使用的在线数据集,因此结果应该是可重现的:

bible <- readLines('http://bereanbible.com/bsb.txt')

这就是一切都崩溃的地方。

输入:

 bible <- bible %>%
      unnest_tokens(word, text)

输出:

Error in tbl[[input]] : subscript out of bounds

根据我所读到的有关此错误的信息,在 Rstudio 中,问题是数据集需要是矩阵,因此我尝试将数据集转换为矩阵 table,但我收到了相同的错误消息.

输入:

 bible <- readLines('http://bereanbible.com/bsb.txt')


bible <- as.matrix(bible, nrow = 31105, ncol = 2 )
      
bible <- bible %>%
  unnest_tokens(word, text)

输出:

Error in tbl[[input]] : subscript out of bounds

对于我可以采取的后续步骤的任何建议,或者在我继续深入研究时可能使用的一些好的文本挖掘资源,将不胜感激。

问题是readLines()创建了一个向量,而不是数据框,正如unnest_tokens()所期望的那样,所以您需要转换它。将经文分开到它自己的栏中也很有帮助:

library(tidytext)
library(tidyverse)

bible_orig <- readLines('http://bereanbible.com/bsb.txt')

# Get rid of the copyright etc.
bible_orig <- bible_orig[4:length(bible_orig)]

# Convert to df
bible <- enframe(bible_orig)

# Separate verse from text
bible <- bible %>% 
 separate(value, into = c("verse", "text"), sep = "\t")

tidy_bible <- bible %>% 
  unnest_tokens(word, text)

tidy_bible
#> # A tibble: 730,130 x 3
#>     name verse       word     
#>    <int> <chr>       <chr>    
#>  1     1 Genesis 1:1 in       
#>  2     1 Genesis 1:1 the      
#>  3     1 Genesis 1:1 beginning
#>  4     1 Genesis 1:1 god      
#>  5     1 Genesis 1:1 created  
#>  6     1 Genesis 1:1 the      
#>  7     1 Genesis 1:1 heavens  
#>  8     1 Genesis 1:1 and      
#>  9     1 Genesis 1:1 the      
#> 10     1 Genesis 1:1 earth    
#> # … with 730,120 more rows

reprex package (v0.3.0)

于 2020-07-14 创建