【问题标题】:Working with large text files in R to create n-grams在 R 中处理大型文本文件以创建 n-gram
【发布时间】:2017-01-09 16:20:58
【问题描述】:

我正在尝试使用 R 编程环境中的 'quanteda' 包从一个大 (1GB) 文本文件创建三元组和二元组。如果我尝试一次性运行我的代码(如下所示),R 就会挂起(在第 3 行 - myCorpus

  folder.dataset.english <- 'final/corpus'


myCorpus <- corpus(x=textfile(list.files(path = folder.dataset.english, pattern = "\\.txt$", full.names = TRUE, recursive = FALSE)))  # build the corpus

myCorpus<-toLower(myCorpus, keepAcronyms = TRUE)

#bigrams
bigrams<-dfm(myCorpus, ngrams = 2,verbose = TRUE, toLower = TRUE,
             removeNumbers = TRUE, removePunct = TRUE, removeSeparators = TRUE,removeTwitter = TRUE, stem = FALSE) 
bigrams_freq<-sort(colSums(bigrams),decreasing=T)
bigrams<-data.frame(names=names(bigrams_freq),freq=bigrams_freq,stringsAsFactors =FALSE)
bigrams$first<- sapply(strsplit(bigrams$names, "_"), "[[", 1)
bigrams$last<-  sapply(strsplit(bigrams$names, "_"), "[[", 2)
rownames(bigrams)<-NULL
bigrams.freq.freq<-table(bigrams$freq)
saveRDS(bigrams,"dictionaries/bigrams.rds")

#trigrams
trigrams<-dfm(myCorpus, ngrams = 3,verbose = TRUE, toLower = TRUE,
              removeNumbers = TRUE, removePunct = TRUE, removeSeparators = TRUE,
              removeTwitter = TRUE, stem = FALSE) 
trigrams_freq<-sort(colSums(trigrams),decreasing=T)
trigrams<-data.frame(names=names(trigrams_freq),freq=trigrams_freq,stringsAsFactors =FALSE)

trigrams$first<-paste(sapply(strsplit(trigrams$names, "_"), "[[", 1),sapply(strsplit(trigrams$names, "_"), "[[", 2),sep="_")
trigrams$last<-sapply(strsplit(trigrams$names, "_"), "[[", 3)
rownames(trigrams)<-NULL
saveRDS(trigrams,"dictionaries/trigrams.rds")

【问题讨论】:

  • 你的代码在什么时候挂起?
  • 它挂在 myCorpus
  • 你的代码能否在较小的数据集上成功运行?
  • 是的,我在一个小数据集上成功运行了它

标签: r nlp


【解决方案1】:

在头疼之后,我自己解决了这个问题,以一种非常暴力的方式,我有点尴尬,但无论如何我都会展示出来!我确信有更优雅和有效的方法(请随时教育我)我只需要处理这个文本一次,所以我想不优雅的解决方案并不重要。

我转换为一个“tm”包 V.Corpus 对象,它由三个大文本文件组成,然后遍历三个文本文件并手动切分语料库一次处理每个块。为了清楚起见,我在这里没有插入和插入上面给出的处理代码。我只是指出了我需要在哪里缝合。我现在需要添加一些代码来累积每个块的结果。

library(tm)

 folder.dataset.english <- 'final/corpus'
    corpus <- VCorpus(DirSource(directory=folder.dataset.english, encoding = "UTF-8",recursive=FALSE),
                      readerControl = list(language = "en"))
    chunk.size<-100000


    for(t in 1:3){
        l=1
        h=chunk.size
        stp=0
        corp.size<-length(corpus[[t]]$content)
          repeat{  
            if(stp==2)break
            corpus.chunk<-corpus[[t]]$content[l:h]
            l<-h+1
            h<-h+chunk.size
    ####Processing code in here


    #####Processing code ends here
            if(h>corp.size){
            h<-corp.size
            stp<-stp+1      }
                  }
                }

【讨论】:

  • 只需使用text2vec::create_vocabulary
  • 好的!没遇到过这个包,我去看看
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-12
  • 2011-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多