SCM

SCM Repository

[tm] Diff of /pkg/R/corpus.R
ViewVC logotype

Diff of /pkg/R/corpus.R

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

trunk/R/textmin/R/textdoccol.R revision 62, Tue Oct 24 10:08:58 2006 UTC pkg/R/corpus.R revision 1108, Fri Oct 22 18:32:47 2010 UTC
# Line 1  Line 1 
1  # Author: Ingo Feinerer  # Author: Ingo Feinerer
2    
3  setGeneric("TextDocCol", function(object, parser = plaintext.parser, lod = FALSE) standardGeneric("TextDocCol"))  .PCorpus <- function(x, cmeta, dmeta, dbcontrol) {
4  setMethod("TextDocCol",      attr(x, "CMetaData") <- cmeta
5            signature(object = "character"),      attr(x, "DMetaData") <- dmeta
6            function(object, parser = plaintext.parser, lod = FALSE) {      attr(x, "DBControl") <- dbcontrol
7                filelist <- dir(object, full.names = TRUE)      class(x) <- c("PCorpus", "Corpus", "list")
8                tdl <- lapply(filelist, parser, lod)      x
9                return(new("TextDocCol", .Data = tdl))  }
10            })  DBControl <- function(x) attr(x, "DBControl")
11    
12  plaintext.parser <- function(file, lod) {  PCorpus <- function(x,
13      id <- file                      readerControl = list(reader = x$DefaultReader, language = "en"),
14      origin <- dirname(file)                      dbControl = list(dbName = "", dbType = "DB1"),
15                        ...) {
16        readerControl <- prepareReader(readerControl, x$DefaultReader, ...)
17    
18        if (!filehash::dbCreate(dbControl$dbName, dbControl$dbType))
19            stop("error in creating database")
20        db <- filehash::dbInit(dbControl$dbName, dbControl$dbType)
21    
22        # Allocate memory in advance if length is known
23        tdl <- if (x$Length > 0)
24            vector("list", as.integer(x$Length))
25        else
26            list()
27    
28      doc <- new("PlainTextDocument", FileName = file, Cached = FALSE, Author = "Unknown",      counter <- 1
29                 DateTimeStamp = date(), Description = "", ID = id, Origin = origin, Heading = "")      while (!eoi(x)) {
30            x <- stepNext(x)
31            elem <- getElem(x)
32            doc <- readerControl$reader(elem, readerControl$language, if (is.null(x$Names)) as.character(counter) else x$Names[counter])
33            filehash::dbInsert(db, ID(doc), doc)
34            if (x$Length > 0) tdl[[counter]] <- ID(doc)
35            else tdl <- c(tdl, ID(doc))
36            counter <- counter + 1
37        }
38        names(tdl) <- x$Names
39    
40        df <- data.frame(MetaID = rep(0, length(tdl)), stringsAsFactors = FALSE)
41        filehash::dbInsert(db, "DMetaData", df)
42        dmeta.df <- data.frame(key = "DMetaData", subset = I(list(NA)))
43    
44        .PCorpus(tdl, .MetaDataNode(), dmeta.df, dbControl)
45    }
46    
47    .VCorpus <- function(x, cmeta, dmeta) {
48        attr(x, "CMetaData") <- cmeta
49        attr(x, "DMetaData") <- dmeta
50        class(x) <- c("VCorpus", "Corpus", "list")
51        x
52    }
53    
54    # Register S3 corpus classes to be recognized by S4 methods. This is
55    # mainly a fix to be compatible with packages which were originally
56    # developed to cooperate with corresponding S4 tm classes. Necessary
57    # since tm's class architecture was changed to S3 since tm version 0.5.
58    setOldClass(c("VCorpus", "Corpus", "list"))
59    
60    # The "..." are additional arguments for the FunctionGenerator reader
61    VCorpus <- Corpus <- function(x,
62                                  readerControl = list(reader = x$DefaultReader, language = "en"),
63                                  ...) {
64        readerControl <- prepareReader(readerControl, x$DefaultReader, ...)
65    
66        # Allocate memory in advance if length is known
67        tdl <- if (x$Length > 0)
68            vector("list", as.integer(x$Length))
69        else
70            list()
71    
72      if (lod) {      if (x$Vectorized)
73          doc <- loadFileIntoMem(doc)          tdl <- mapply(function(x, id) readerControl$reader(x, readerControl$language, id),
74                          pGetElem(x),
75                          id = if (is.null(x$Names)) as.character(seq_len(x$Length)) else x$Names,
76                          SIMPLIFY = FALSE)
77        else {
78            counter <- 1
79            while (!eoi(x)) {
80                x <- stepNext(x)
81                elem <- getElem(x)
82                doc <- readerControl$reader(elem, readerControl$language, if (is.null(x$Names)) as.character(counter) else x$Names[counter])
83                if (x$Length > 0)
84                    tdl[[counter]] <- doc
85                else
86                    tdl <- c(tdl, list(doc))
87                counter <- counter + 1
88            }
89        }
90        names(tdl) <- x$Names
91        df <- data.frame(MetaID = rep(0, length(tdl)), stringsAsFactors = FALSE)
92        .VCorpus(tdl, .MetaDataNode(), df)
93      }      }
94    
95      return(doc)  `[.PCorpus` <- function(x, i) {
96        if (missing(i)) return(x)
97        index <- attr(x, "DMetaData")[[1 , "subset"]]
98        attr(x, "DMetaData")[[1 , "subset"]] <- if (is.numeric(index)) index[i] else i
99        dmeta <- attr(x, "DMetaData")
100        .PCorpus(NextMethod("["), CMetaData(x), dmeta, DBControl(x))
101  }  }
102    
103  reuters21578xml.parser <- function(file, lod) {  `[.VCorpus` <- function(x, i) {
104      tree <- xmlTreeParse(file)      if (missing(i)) return(x)
105      node <- xmlRoot(tree)      .VCorpus(NextMethod("["), CMetaData(x), DMetaData(x)[i, , drop = FALSE])
106    }
107    
108      # The <AUTHOR></AUTHOR> tag is unfortunately NOT obligatory!  `[<-.PCorpus` <- function(x, i, value) {
109      if (!is.null(node[["TEXT"]][["AUTHOR"]]))      db <- filehash::dbInit(DBControl(x)[["dbName"]], DBControl(x)[["dbType"]])
110          author <- xmlValue(node[["TEXT"]][["AUTHOR"]])      counter <- 1
111      else      for (id in unclass(x)[i]) {
112          author <- ""          if (identical(length(value), 1L)) db[[id]] <- value
113            else db[[id]] <- value[[counter]]
114            counter <- counter + 1
115        }
116        x
117    }
118    
119      datetimestamp <- xmlValue(node[["DATE"]])  .map_name_index <- function(x, i) {
120      description <- ""      if (is.character(i)) {
121      id <- xmlAttrs(node)[["NEWID"]]          if (is.null(names(x)))
122                match(i, meta(x, "ID", type = "local"))
     # The <TITLE></TITLE> tag is unfortunately NOT obligatory!  
     if (!is.null(node[["TEXT"]][["TITLE"]]))  
         heading <- xmlValue(node[["TEXT"]][["TITLE"]])  
123      else      else
124          heading <- ""              match(i, names(x))
   
     topics <- unlist(xmlApply(node[["TOPICS"]], function(x) xmlValue(x)), use.names = FALSE)  
   
     doc <- new("XMLTextDocument", FileName = file, Cached = FALSE, Author = author,  
                DateTimeStamp = datetimestamp, Description = "", ID = id, Origin = "Reuters-21578 XML",  
                Heading = heading, LocalMetaData = list(Topics = topics))  
   
     if (lod) {  
         doc <- loadFileIntoMem(doc)  
125      }      }
126        i
     return(doc)  
127  }  }
128    
129  rcv1.parser <- function(file, lod) {  `[[.PCorpus` <-  function(x, i) {
130      tree <- xmlTreeParse(file)      i <- .map_name_index(x, i)
131      node <- xmlRoot(tree)      db <- filehash::dbInit(DBControl(x)[["dbName"]], DBControl(x)[["dbType"]])
132        filehash::dbFetch(db, NextMethod("[["))
133    }
134    `[[.VCorpus` <-  function(x, i) {
135        i <- .map_name_index(x, i)
136        lazyTmMap <- meta(x, tag = "lazyTmMap", type = "corpus")
137        if (!is.null(lazyTmMap))
138            .Call("copyCorpus", x, materialize(x, i))
139        NextMethod("[[")
140    }
141    
142      datetimestamp <- xmlAttrs(node)[["date"]]  `[[<-.PCorpus` <-  function(x, i, value) {
143      id <- xmlAttrs(node)[["itemid"]]      i <- .map_name_index(x, i)
144      heading <- xmlValue(node[["title"]])      db <- filehash::dbInit(DBControl(x)[["dbName"]], DBControl(x)[["dbType"]])
145        index <- unclass(x)[[i]]
146        db[[index]] <- value
147        x
148    }
149    `[[<-.VCorpus` <-  function(x, i, value) {
150        i <- .map_name_index(x, i)
151        # Mark new objects as not active for lazy mapping
152        lazyTmMap <- meta(x, tag = "lazyTmMap", type = "corpus")
153        if (!is.null(lazyTmMap)) {
154            lazyTmMap$index[i] <- FALSE
155            meta(x, tag = "lazyTmMap", type = "corpus") <- lazyTmMap
156        }
157        # Set the value
158        cl <- class(x)
159        y <- NextMethod("[[<-")
160        class(y) <- cl
161        y
162    }
163    
164      doc <- new("XMLTextDocument", FileName = file, Cached = FALSE, Author = "",  # Update NodeIDs of a CMetaData tree
165                 DateTimeStamp = datetimestamp, Description = "", ID = id, Origin = "Reuters Corpus Volume 1 XML",  .update_id <- function(x, id = 0, mapping = NULL, left.mapping = NULL, level = 0) {
166                 Heading = heading)      # Traversal of (binary) CMetaData tree with setup of NodeIDs
167        set_id <- function(x) {
168            x$NodeID <- id
169            id <<- id + 1
170            level <<- level + 1
171            if (length(x$Children) > 0) {
172                mapping <<- cbind(mapping, c(x$Children[[1]]$NodeID, id))
173                left <- set_id(x$Children[[1]])
174                if (level == 1) {
175                    left.mapping <<- mapping
176                    mapping <<- NULL
177                }
178                mapping <<- cbind(mapping, c(x$Children[[2]]$NodeID, id))
179                right <- set_id(x$Children[[2]])
180    
181      if (lod) {              x$Children <- list(left, right)
182          doc <- loadFileIntoMem(doc)          }
183            level <<- level - 1
184            x
185        }
186        list(root = set_id(x), left.mapping = left.mapping, right.mapping = mapping)
187      }      }
188    
189      return(doc)  # Find indices to be updated for a CMetaData tree
190    .find_indices <- function(x) {
191        indices.mapping <- NULL
192        for (m in levels(as.factor(DMetaData(x)$MetaID))) {
193            indices <- (DMetaData(x)$MetaID == m)
194            indices.mapping <- c(indices.mapping, list(m = indices))
195            names(indices.mapping)[length(indices.mapping)] <- m
196        }
197        indices.mapping
198  }  }
199    
200  uci.kdd.newsgroup.parser <-  function(file, lod) {  c2 <- function(x, y, ...) {
201      mail <- readLines(file)      # Update the CMetaData tree
202      author <- gsub("From: ", "", grep("^From:", mail, value = TRUE))      cmeta <- .MetaDataNode(0, list(merge_date = as.POSIXlt(Sys.time(), tz = "GMT"), merger = Sys.getenv("LOGNAME")), list(CMetaData(x), CMetaData(y)))
203      datetimestamp <- gsub("Date: ", "", grep("^Date:", mail, value = TRUE))      update.struct <- .update_id(cmeta)
     origin <- gsub("Path: ", "", grep("^Path:", mail, value = TRUE))  
     heading <- gsub("Subject: ", "", grep("^Subject:", mail, value = TRUE))  
     newsgroup <- gsub("Newsgroups: ", "", grep("^Newsgroups:", mail, value = TRUE))  
204    
205      new("NewsgroupDocument", FileName = file, Cached = FALSE, Author = author, DateTimeStamp = datetimestamp,      new <- .VCorpus(c(unclass(x), unclass(y)), update.struct$root, NULL)
         Description = "", ID = file, Origin = origin, Heading = heading, Newsgroup = newsgroup)  
206    
207      if (lod) {      # Find indices to be updated for the left tree
208          doc <- loadFileIntoMem(doc)      indices.mapping <- .find_indices(x)
     }  
209    
210      return(doc)      # Update the DMetaData data frames for the left tree
211        for (i in 1:ncol(update.struct$left.mapping)) {
212            map <- update.struct$left.mapping[,i]
213            DMetaData(x)$MetaID <- replace(DMetaData(x)$MetaID, indices.mapping[[as.character(map[1])]], map[2])
214  }  }
215    
216  # Parse a <newsitem></newsitem> element from a well-formed RCV1 XML file      # Find indices to be updated for the right tree
217  rcv1.to.plain <- function(node) {      indices.mapping <- .find_indices(y)
     datetimestamp <- xmlAttrs(node)[["date"]]  
     id <- xmlAttrs(node)[["itemid"]]  
     origin <- "Reuters Corpus Volume 1 XML"  
     corpus <- unlist(xmlApply(node[["text"]], xmlValue), use.names = FALSE)  
     heading <- xmlValue(node[["title"]])  
218    
219      new("PlainTextDocument", .Data = corpus, Author = "", DateTimeStamp = datetimestamp,      # Update the DMetaData data frames for the right tree
220          Description = "", ID = id, Origin = "Reuters Corpus Volume 1 XML", Heading = heading)      for (i in 1:ncol(update.struct$right.mapping)) {
221            map <- update.struct$right.mapping[,i]
222            DMetaData(y)$MetaID <- replace(DMetaData(y)$MetaID, indices.mapping[[as.character(map[1])]], map[2])
223  }  }
224    
225  # Parse a <REUTERS></REUTERS> element from a well-formed Reuters-21578 XML file      # Merge the DMetaData data frames
226  reuters21578xml.to.plain <- function(node) {      labels <- setdiff(names(DMetaData(y)), names(DMetaData(x)))
227      # The <AUTHOR></AUTHOR> tag is unfortunately NOT obligatory!      na.matrix <- matrix(NA, nrow = nrow(DMetaData(x)), ncol = length(labels), dimnames = list(row.names(DMetaData(x)), labels))
228      if (!is.null(node[["TEXT"]][["AUTHOR"]]))      x.dmeta.aug <- cbind(DMetaData(x), na.matrix)
229          author <- xmlValue(node[["TEXT"]][["AUTHOR"]])      labels <- setdiff(names(DMetaData(x)), names(DMetaData(y)))
230      else      na.matrix <- matrix(NA, nrow = nrow(DMetaData(y)), ncol = length(labels), dimnames = list(row.names(DMetaData(y)), labels))
231          author <- ""      y.dmeta.aug <- cbind(DMetaData(y), na.matrix)
232        DMetaData(new) <- rbind(x.dmeta.aug, y.dmeta.aug)
233    
234      datetimestamp <- xmlValue(node[["DATE"]])      new
235      description <- ""  }
     id <- xmlAttrs(node)[["NEWID"]]  
236    
237      origin <- "Reuters-21578 XML"  c.Corpus <-
238    function(x, ..., recursive = FALSE)
239    {
240        args <- list(...)
241    
242      # The <BODY></BODY> tag is unfortunately NOT obligatory!      if (identical(length(args), 0L))
243      if (!is.null(node[["TEXT"]][["BODY"]]))          return(x)
         corpus <- xmlValue(node[["TEXT"]][["BODY"]])  
     else  
         corpus <- ""  
244    
245      # The <TITLE></TITLE> tag is unfortunately NOT obligatory!      if (!all(unlist(lapply(args, inherits, class(x)))))
246      if (!is.null(node[["TEXT"]][["TITLE"]]))          stop("not all arguments are of the same corpus type")
         heading <- xmlValue(node[["TEXT"]][["TITLE"]])  
     else  
         heading <- ""  
247    
248      topics <- unlist(xmlApply(node[["TOPICS"]], function(x) xmlValue(x)), use.names = FALSE)      if (inherits(x, "PCorpus"))
249            stop("concatenation of corpora with underlying databases is not supported")
250    
251      new("PlainTextDocument", .Data = corpus, Cached = TRUE, Author = author, DateTimeStamp = datetimestamp,      l <- base::c(list(x), args)
252          Description = description, ID = id, Origin = origin, Heading = heading, LocalMetaData = list(Topics = topics))      if (recursive)
253            Reduce(c2, l)
254        else {
255            l <- do.call("c", lapply(l, unclass))
256            .VCorpus(l,
257                     cmeta = .MetaDataNode(),
258                     dmeta = data.frame(MetaID = rep(0, length(l)), stringsAsFactors = FALSE))
259        }
260  }  }
261    
262  setGeneric("loadFileIntoMem", function(object) standardGeneric("loadFileIntoMem"))  c.TextDocument <- function(x, ..., recursive = FALSE) {
263  setMethod("loadFileIntoMem",      args <- list(...)
           signature(object = "PlainTextDocument"),  
           function(object) {  
               if (!Cached(object)) {  
                   corpus <- readLines(FileName(object))  
                   Corpus(object) <- corpus  
                   Cached(object) <- TRUE  
                   return(object)  
               } else {  
                   return(object)  
               }  
           })  
 setMethod("loadFileIntoMem",  
           signature(object =  "XMLTextDocument"),  
           function(object) {  
               if (!Cached(object)) {  
                   file <- FileName(object)  
                   doc <- xmlTreeParse(file)  
                   class(doc) <- "list"  
                   Corpus(object) <- doc  
                   Cached(object) <- TRUE  
                   return(object)  
               } else {  
                   return(object)  
               }  
           })  
 setMethod("loadFileIntoMem",  
           signature(object = "NewsgroupDocument"),  
           function(object) {  
               if (!Cached(object)) {  
                   mail <- readLines(FileName(object))  
                   Cached(object) <- TRUE  
                   index <- grep("^Lines:", mail)  
                   Corpus(object) <- mail[(index + 1):length(mail)]  
                   return(object)  
               } else {  
                   return(object)  
               }  
           })  
   
 setGeneric("tm_transform", function(object, FUN, ...) standardGeneric("tm_transform"))  
 setMethod("tm_transform",  
           signature(object = "TextDocCol", FUN = "function"),  
           function(object, FUN, ...) {  
               result <- as(lapply(object, FUN, ..., GlobalMetaData = GlobalMetaData(object)), "TextDocCol")  
               result@GlobalMetaData <- GlobalMetaData(object)  
               return(result)  
           })  
   
 setGeneric("toPlainTextDocument", function(object, FUN, ...) standardGeneric("toPlainTextDocument"))  
 setMethod("toPlainTextDocument",  
           signature(object = "PlainTextDocument"),  
           function(object, FUN, ...) {  
               return(object)  
           })  
 setMethod("toPlainTextDocument",  
           signature(object = "XMLTextDocument", FUN = "function"),  
           function(object, FUN, ...) {  
               if (!Cached(object))  
                   object <- loadFileIntoMem(object)  
   
               corpus <- Corpus(object)  
   
               # As XMLDocument is no native S4 class, restore valid information  
               class(corpus) <- "XMLDocument"  
               names(corpus) <- c("doc","dtd")  
   
               return(FUN(xmlRoot(corpus), ...))  
           })  
   
 setGeneric("stemTextDocument", function(object, ...) standardGeneric("stemTextDocument"))  
 setMethod("stemTextDocument",  
           signature(object = "PlainTextDocument"),  
           function(object, ...) {  
               if (!Cached(object))  
                   object <- loadFileIntoMem(object)  
   
               require(Rstem)  
               splittedCorpus <- unlist(strsplit(object, " ", fixed = TRUE))  
               stemmedCorpus <- wordStem(splittedCorpus, ...)  
               Corpus(object) <- paste(stemmedCorpus, collapse = " ")  
               return(object)  
           })  
   
 setGeneric("removeStopWords", function(object, stopwords, ...) standardGeneric("removeStopWords"))  
 setMethod("removeStopWords",  
           signature(object = "PlainTextDocument", stopwords = "character"),  
           function(object, stopwords, ...) {  
               if (!Cached(object))  
                   object <- loadFileIntoMem(object)  
   
               require(Rstem)  
               splittedCorpus <- unlist(strsplit(object, " ", fixed = TRUE))  
               noStopwordsCorpus <- splittedCorpus[!splittedCorpus %in% stopwords]  
               Corpus(object) <- paste(noStopwordsCorpus, collapse = " ")  
               return(object)  
           })  
   
 setGeneric("tm_filter", function(object, ..., FUN = s.filter) standardGeneric("tm_filter"))  
 setMethod("tm_filter",  
           signature(object = "TextDocCol"),  
           function(object, ..., FUN = s.filter) {  
               object[tm_index(object, ..., FUN)]  
           })  
   
 setGeneric("tm_index", function(object, ..., FUN = s.filter) standardGeneric("tm_index"))  
 setMethod("tm_index",  
           signature(object = "TextDocCol"),  
           function(object, ..., FUN = s.filter) {  
               sapply(object, FUN, ..., GlobalMetaData = GlobalMetaData(object))  
           })  
   
 s.filter <- function(object, s, ..., GlobalMetaData) {  
     b <- TRUE  
     for (tag in names(s)) {  
         if (tag %in% names(LocalMetaData(object))) {  
             b <- b && any(grep(s[[tag]], LocalMetaData(object)[[tag]]))  
         } else if (tag %in% names(GlobalMetaData)){  
             b <- b && any(grep(s[[tag]], GlobalMetaData[[tag]]))  
         } else {  
             b <- b && any(grep(s[[tag]], eval(call(tag, object))))  
         }  
     }  
     return(b)  
 }  
   
 setGeneric("fulltext.search.filter", function(object, pattern, ...) standardGeneric("fulltext.search.filter"))  
 setMethod("fulltext.search.filter",  
           signature(object = "PlainTextDocument", pattern = "character"),  
           function(object, pattern, ...) {  
               if (!Cached(object))  
                   object <- loadFileIntoMem(object)  
   
               return(any(grep(pattern, Corpus(object))))  
           })  
   
 setGeneric("reuters21578.topic.filter", function(object, topics, ...) standardGeneric("reuters21578.topic.filter"))  
 setMethod("reuters21578.topic.filter",  
           signature(object = "PlainTextDocument", topics = "character"),  
           function(object, topics, ...) {  
               if (!Cached(object))  
                   object <- loadFileIntoMem(object)  
264    
265                if (any(LocalMetaData(object)$Topics %in% topics))      if (identical(length(args), 0L))
266                    return(TRUE)          return(x)
               else  
                   return(FALSE)  
           })  
267    
268  setGeneric("id.filter", function(object, IDs, ...) standardGeneric("id.filter"))      if (!all(unlist(lapply(args, inherits, class(x)))))
269  setMethod("id.filter",          stop("not all arguments are text documents")
           signature(object = "TextDocument", IDs = "numeric"),  
           function(object, IDs, ...) {  
               if (ID(object) %in% IDs)  
                   return(TRUE)  
               else  
                   return(FALSE)  
           })  
270    
271  setGeneric("attachData", function(object, data) standardGeneric("attachData"))      dmeta <- data.frame(MetaID = rep(0, length(list(x, ...))), stringsAsFactors = FALSE)
272  setMethod("attachData",      .VCorpus(list(x, ...), .MetaDataNode(), dmeta)
273            signature(object = "TextDocCol", data = "TextDocument"),  }
           function(object, data) {  
               data <- as(list(data), "TextDocCol")  
               object@.Data <- as(c(object@.Data, data), "TextDocCol")  
               return(object)  
           })  
   
 setGeneric("attachMetaData", function(object, name, metadata) standardGeneric("attachMetaData"))  
 setMethod("attachMetaData",  
           signature(object = "TextDocCol"),  
           function(object, name, metadata) {  
               object@GlobalMetaData <- c(GlobalMetaData(object), new = list(metadata))  
               names(object@GlobalMetaData)[length(names(GlobalMetaData(object)))] <- name  
               return(object)  
           })  
   
 setGeneric("setSubscriptable", function(object, name) standardGeneric("setSubscriptable"))  
 setMethod("setSubscriptable",  
           signature(object = "TextDocCol"),  
           function(object, name) {  
               if (!is.character(GlobalMetaData(object)$subscriptable))  
                   object <- attachMetaData(object, "subscriptable", name)  
               else  
                   object@GlobalMetaData$subscriptable <- c(GlobalMetaData(object)$subscriptable, name)  
               return(object)  
           })  
   
 setMethod("[",  
           signature(x = "TextDocCol", i = "ANY", j = "ANY", drop = "ANY"),  
           function(x, i, j, ... , drop) {  
               if(missing(i))  
                   return(x)  
274    
275                object <- x  print.Corpus <- function(x, ...) {
276                object@.Data <- x@.Data[i, ..., drop = FALSE]      cat(sprintf(ngettext(length(x),
277                for (m in names(GlobalMetaData(object))) {                           "A corpus with %d text document\n",
278                    if (m %in% GlobalMetaData(object)$subscriptable) {                           "A corpus with %d text documents\n"),
279                        object@GlobalMetaData[[m]] <- GlobalMetaData(object)[[m]][i, ..., drop = FALSE]                  length(x)))
280        invisible(x)
281    }
282    
283    summary.Corpus <- function(object, ...) {
284        print(object)
285        if (length(DMetaData(object)) > 0) {
286            cat(sprintf(ngettext(length(attr(CMetaData(object), "MetaData")),
287                                 "\nThe metadata consists of %d tag-value pair and a data frame\n",
288                                 "\nThe metadata consists of %d tag-value pairs and a data frame\n"),
289                        length(CMetaData(object)$MetaData)))
290            cat("Available tags are:\n")
291            cat(strwrap(paste(names(CMetaData(object)$MetaData), collapse = " "), indent = 2, exdent = 2), "\n")
292            cat("Available variables in the data frame are:\n")
293            cat(strwrap(paste(names(DMetaData(object)), collapse = " "), indent = 2, exdent = 2), "\n")
294                    }                    }
295                }                }
               return(object)  
           })  
   
 setMethod("c",  
           signature(x = "TextDocCol"),  
           function(x, ..., recursive = TRUE){  
               args <- list(...)  
               if(length(args) == 0)  
                   return(x)  
               return(as(c(as(x, "list"), ...), "TextDocCol"))  
     })  
296    
297  setMethod("length",  inspect <- function(x) UseMethod("inspect", x)
298            signature(x = "TextDocCol"),  inspect.PCorpus <- function(x) {
299            function(x){      summary(x)
               return(length(as(x, "list")))  
     })  
   
 setMethod("show",  
           signature(object = "TextDocCol"),  
           function(object){  
               cat("A text document collection with", length(object), "text document")  
               if (length(object) == 1)  
300                    cat("\n")                    cat("\n")
301                else      db <- filehash::dbInit(DBControl(x)[["dbName"]], DBControl(x)[["dbType"]])
302                    cat("s\n")      show(filehash::dbMultiFetch(db, unlist(x)))
     })  
   
 setMethod("summary",  
           signature(object = "TextDocCol"),  
           function(object){  
               show(object)  
               if (length(GlobalMetaData(object)) > 0) {  
                   cat("\nThe global metadata consists of", length(GlobalMetaData(object)), "tag-value pair")  
                   if (length(GlobalMetaData(object)) == 1)  
                       cat(".\n")  
                   else  
                       cat("s.\n")  
                   cat("Available tags are:\n")  
                   cat(names(GlobalMetaData(object)), "\n")  
303                }                }
304      })  inspect.VCorpus <- function(x) {
305        summary(x)
 setGeneric("inspect", function(object) standardGeneric("inspect"))  
 setMethod("inspect",  
           c("TextDocCol"),  
           function(object) {  
               summary(object)  
306                cat("\n")                cat("\n")
307                show(as(object, "list"))      print(noquote(lapply(x, identity)))
308            })  }
309    
310    lapply.PCorpus <- function(X, FUN, ...) {
311        db <- filehash::dbInit(DBControl(X)[["dbName"]], DBControl(X)[["dbType"]])
312        lapply(filehash::dbMultiFetch(db, unlist(X)), FUN, ...)
313    }
314    lapply.VCorpus <- function(X, FUN, ...) {
315        lazyTmMap <- meta(X, tag = "lazyTmMap", type = "corpus")
316        if (!is.null(lazyTmMap))
317            .Call("copyCorpus", X, materialize(X))
318        base::lapply(X, FUN, ...)
319    }
320    
321    writeCorpus <-  function(x, path = ".", filenames = NULL) {
322        filenames <- file.path(path,
323                               if (is.null(filenames)) unlist(lapply(x, function(x) sprintf("%s.txt", ID(x))))
324                               else filenames)
325        i <- 1
326        for (o in x) {
327            writeLines(as.PlainTextDocument(o), filenames[i])
328            i <- i + 1
329        }
330    }

Legend:
Removed from v.62  
changed lines
  Added in v.1108

root@r-forge.r-project.org
ViewVC Help
Powered by ViewVC 1.0.0  
Thanks to:
Vienna University of Economics and Business Powered By FusionForge