首页 > 解决方案 > txt 中阅读中文时出错:corpus() 仅适用于字符、语料库、语料库、data.frame、kwic 对象

问题描述

我尝试使用 R、jiebaR 和语料库生成词云并获取中文语音的词频,但无法制作语料库。这是我的代码:

library(jiebaR)
library(stringr)
library(corpus)

cutter <- worker()

v36 <- readLines('v36.txt', encoding = 'UTF-8')

seg_x <- function(x) {str_c(cutter[x], collapse = '')}

x.out <- sapply(v36, seg_x, USE.NAMES = FALSE)

v36.seg <- x.out
v36.seg

library(quanteda)

corpus <- corpus(v36.seg)  #Error begins here.
summary(corpus, showmeta = TRUE, 1)
texts(corpus)[1]

tokens(corpus, what = 'fasterword')[1]

tokens <- tokens(v36.seg, what = 'fasterword')
dfm <- dfm(tokens)
dfm


我的文本文件包含以下段落:

在此处输入图像描述

创建语料库时出现错误。R返回:

Error in corpus.default(v36.seg) : 
  corpus() only works on character, corpus, Corpus, data.frame, kwic objects.

我不明白为什么文本有问题。如果您能帮我解决问题,不胜感激。谢谢你。

标签: rtext-miningstringrcorpusquanteda

解决方案


鉴于您在评论中的文本示例,我将它们放在一个文本文件中。接下来按照 Ken 的说明,您将看到该文本在 quanteda 中很好地提供。从那里你可以做你需要的所有 NLP。请查看quanteda 参考页面上的中文示例。

免责声明:我似乎无法将您评论中的中文示例文本粘贴到此答案中,因为系统认为我在放入垃圾邮件:-(

library(quanteda)
library(readtext)

v36 <- readtext::readtext("v36.txt", encoding = "UTF8")

my_dfm <- v36 %>%  corpus() %>%
  tokens(what = "word") %>%
  dfm()  

# show frequency to check if words are available.
dplyr::as_tibble(textstat_frequency(my_dfm))

# A tibble: 79 x 5
   feature frequency  rank docfreq group
   <chr>       <dbl> <int>   <dbl> <chr>
 1 ,              6     1       1 all  
 2 政府            6     1       1 all  
 3 。              5     3       1 all  
 4 在              3     4       1 all  
 5 的              3     4       1 all  
 6 安排            3     4       1 all  
 7 發言人          2     7       1 all  
 8 (              2     7       1 all  
 9 一月            2     7       1 all  
10 )              2     7       1 all  
# ... with 69 more rows

推荐阅读