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 66, Tue Oct 31 22:03:33 2006 UTC pkg/R/corpus.R revision 1021, Tue Nov 17 16:37:22 2009 UTC
# Line 1  Line 1 
1  # Author: Ingo Feinerer  # Author: Ingo Feinerer
2    
3  # The "..." are additional arguments for the function_generator parser  .PCorpus <- function(x, cmeta, dmeta, dbcontrol) {
4  setGeneric("TextDocCol", function(object, parser = plaintext_parser, ...) standardGeneric("TextDocCol"))      attr(x, "CMetaData") <- cmeta
5  setMethod("TextDocCol",      attr(x, "DMetaData") <- dmeta
6            signature(object = "Source"),      attr(x, "DBControl") <- dbcontrol
7            function(object, parser = plaintext_parser) {      class(x) <- c("PCorpus", "Corpus", "list")
8                if (inherits(parser, "function_generator"))      x
9                    parser <- parser(...)  }
10    DBControl <- function(x) attr(x, "DBControl")
11    
12    PCorpus <- function(x,
13                        readerControl = list(reader = x$DefaultReader, language = "eng"),
14                        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    
               tdl <- list()  
28                counter <- 1                counter <- 1
29                while (!eoi(object)) {      while (!eoi(x)) {
30                    object <- step_next(object)          x <- stepNext(x)
31                    elem <- get_elem(object)          elem <- getElem(x)
32                    # If there is no Load on Demand support          doc <- readerControl$reader(elem, readerControl$language, as.character(counter))
33                    # we need to load the corpus into memory at startup          filehash::dbInsert(db, ID(doc), doc)
34                    if (object@LoDSupport)          if (x$Length > 0) tdl[[counter]] <- ID(doc)
35                        load <- object@Load          else tdl <- c(tdl, ID(doc))
                   else  
                       load <- TRUE  
                   tdl <- c(tdl, list(parser(elem, object@LoDSupport, load, as.character(counter))))  
36                    counter <- counter + 1                    counter <- counter + 1
37                }                }
38    
39                return(new("TextDocCol", .Data = tdl))      df <- data.frame(MetaID = rep(0, length(tdl)), stringsAsFactors = FALSE)
40            })      filehash::dbInsert(db, "DMetaData", df)
41        dmeta.df <- data.frame(key = "DMetaData", subset = I(list(NA)))
42  setGeneric("DirSource", function(directory, load = FALSE) standardGeneric("DirSource"))  
43  setMethod("DirSource",      .PCorpus(tdl, .MetaDataNode(), dmeta.df, dbControl)
44            signature(directory = "character"),  }
45            function(directory, load = FALSE) {  
46                new("DirSource", LoDSupport = TRUE, FileList = dir(directory, full.names = TRUE),  .VCorpus <- function(x, cmeta, dmeta) {
47                    Position = 0, Load = load)      attr(x, "CMetaData") <- cmeta
48            })      attr(x, "DMetaData") <- dmeta
49        class(x) <- c("VCorpus", "Corpus", "list")
50  setGeneric("CSVSource", function(object, isConCall = FALSE) standardGeneric("CSVSource"))      x
51  setMethod("CSVSource",  }
52            signature(object = "character"),  
53            function(object, isConCall = FALSE) {  # Register S3 corpus classes to be recognized by S4 methods. This is
54                if (!isConCall)  # mainly a fix to be compatible with packages which were originally
55                    object <- paste('file("', object, '")', sep = "")  # developed to cooperate with corresponding S4 tm classes. Necessary
56                con <- eval(parse(text = object))  # since tm's class architecture was changed to S3 since tm version 0.5.
57                content <- scan(con, what = "character")  setOldClass(c("VCorpus", "Corpus", "list"))
58                close(con)  
59                new("CSVSource", LoDSupport = FALSE, URI = object,  # The "..." are additional arguments for the FunctionGenerator reader
60                    Content = content, Position = 0)  VCorpus <- Corpus <- function(x,
61            })                      readerControl = list(reader = x$DefaultReader, language = "eng"),
62                        ...) {
63  setGeneric("ReutersSource", function(object, isConCall = FALSE) standardGeneric("ReutersSource"))      readerControl <- prepareReader(readerControl, x$DefaultReader, ...)
64  setMethod("ReutersSource",  
65            signature(object = "character"),      # Allocate memory in advance if length is known
66            function(object, isConCall = FALSE) {      tdl <- if (x$Length > 0)
67                if (!isConCall)          vector("list", as.integer(x$Length))
68                   object <- paste('file("', object, '")', sep = "")      else
69                con <- eval(parse(text = object))          list()
70                corpus <- paste(readLines(con), "\n", collapse = "")  
71                close(con)      if (x$Vectorized)
72                tree <- xmlTreeParse(corpus, asText = TRUE)          tdl <- mapply(function(x, id) readerControl$reader(x, readerControl$language, id),
73                content <- xmlRoot(tree)$children                        pGetElem(x),
74                          id = as.character(seq_len(x$Length)),
75                new("ReutersSource", LoDSupport = FALSE, URI = object,                        SIMPLIFY = FALSE)
76                    Content = content, Position = 0)      else {
77            })          counter <- 1
78            while (!eoi(x)) {
79  setGeneric("step_next", function(object) standardGeneric("step_next"))              x <- stepNext(x)
80  setMethod("step_next",              elem <- getElem(x)
81            signature(object = "DirSource"),              doc <- readerControl$reader(elem, readerControl$language, as.character(counter))
82            function(object) {              if (x$Length > 0)
83                object@Position <- object@Position + 1                  tdl[[counter]] <- doc
               object  
           })  
 setMethod("step_next",  
           signature(object = "CSVSource"),  
           function(object) {  
               object@Position <- object@Position + 1  
               object  
           })  
 setMethod("step_next",  
           signature(object = "ReutersSource"),  
           function(object) {  
               object@Position <- object@Position + 1  
               object  
           })  
   
 setGeneric("get_elem", function(object) standardGeneric("get_elem"))  
 setMethod("get_elem",  
           signature(object = "DirSource"),  
           function(object) {  
               list(content = readLines(object@FileList[object@Position]),  
                    uri = paste('file("', object@FileList[object@Position], '")', sep = ""))  
           })  
 setMethod("get_elem",  
           signature(object = "CSVSource"),  
           function(object) {  
               list(content = object@Content[object@Position],  
                    uri = object@URI)  
           })  
 setMethod("get_elem",  
           signature(object = "ReutersSource"),  
           function(object) {  
               # Construct a character representation from the XMLNode  
               con <- textConnection("virtual.file", "w")  
               saveXML(object@Content[[object@Position]], con)  
               close(con)  
   
               list(content = virtual.file, uri = object@URI)  
           })  
   
 setGeneric("eoi", function(object) standardGeneric("eoi"))  
 setMethod("eoi",  
           signature(object = "DirSource"),  
           function(object) {  
               if (length(object@FileList) <= object@Position)  
                   return(TRUE)  
               else  
                   return(FALSE)  
           })  
 setMethod("eoi",  
           signature(object = "CSVSource"),  
           function(object) {  
               if (length(object@Content) <= object@Position)  
                   return(TRUE)  
               else  
                   return(FALSE)  
           })  
 setMethod("eoi",  
           signature(object = "ReutersSource"),  
           function(object) {  
               if (length(object@Content) <= object@Position)  
                   return(TRUE)  
84                else                else
85                    return(FALSE)                  tdl <- c(tdl, list(doc))
86            })              counter <- counter + 1
   
 plaintext_parser <- function(...) {  
     function(elem, lodsupport, load, id) {  
         if (!lodsupport || (lodsupport && load)) {  
             doc <- new("PlainTextDocument", .Data = elem$content, URI = elem$uri, Cached = TRUE,  
                        Author = "", DateTimeStamp = date(), Description = "", ID = id, Origin = "", Heading = "")  
87          }          }
         else {  
             doc <- new("PlainTextDocument", URI = elem$uri, Cached = FALSE,  
                        Author = "", DateTimeStamp = date(), Description = "", ID = id, Origin = "", Heading = "")  
88          }          }
89    
90          return(doc)      df <- data.frame(MetaID = rep(0, length(tdl)), stringsAsFactors = FALSE)
91      }      .VCorpus(tdl, .MetaDataNode(), df)
92  }  }
 class(plaintext_parser) <- "function_generator"  
93    
94  reut21578xml_parser <- function(...) {  `[.PCorpus` <- function(x, i) {
95      function(elem, lodsupport, load, id) {      if (missing(i)) return(x)
96          corpus <- paste(elem$content, "\n", collapse = "")      index <- attr(x, "DMetaData")[[1 , "subset"]]
97          tree <- xmlTreeParse(corpus, asText = TRUE)      attr(x, "DMetaData")[[1 , "subset"]] <- if (is.numeric(index)) index[i] else i
98          node <- xmlRoot(tree)      dmeta <- attr(x, "DMetaData")
99        .PCorpus(NextMethod("["), CMetaData(x), dmeta, DBControl(x))
100          # Mask as list to bypass S4 checks  }
         class(tree) <- "list"  
   
         # The <AUTHOR></AUTHOR> tag is unfortunately NOT obligatory!  
         if (!is.null(node[["TEXT"]][["AUTHOR"]]))  
             author <- xmlValue(node[["TEXT"]][["AUTHOR"]])  
         else  
             author <- ""  
   
         datetimestamp <- xmlValue(node[["DATE"]])  
         description <- ""  
         id <- xmlAttrs(node)[["NEWID"]]  
   
         # The <TITLE></TITLE> tag is unfortunately NOT obligatory!  
         if (!is.null(node[["TEXT"]][["TITLE"]]))  
             heading <- xmlValue(node[["TEXT"]][["TITLE"]])  
         else  
             heading <- ""  
   
         topics <- unlist(xmlApply(node[["TOPICS"]], function(x) xmlValue(x)), use.names = FALSE)  
101    
102          if (!lodsupport || (lodsupport && load)) {  `[.VCorpus` <- function(x, i) {
103              doc <- new("XMLTextDocument", .Data = tree, URI = elem$uri, Cached = TRUE, Author = author,      if (missing(i)) return(x)
104                         DateTimeStamp = datetimestamp, Description = "", ID = id, Origin = "Reuters-21578 XML",      .VCorpus(NextMethod("["), CMetaData(x), DMetaData(x)[i, , drop = FALSE])
                        Heading = heading, LocalMetaData = list(Topics = topics))  
         } else {  
             doc <- new("XMLTextDocument", URI = elem$uri, Cached = FALSE, Author = author,  
                        DateTimeStamp = datetimestamp, Description = "", ID = id, Origin = "Reuters-21578 XML",  
                        Heading = heading, LocalMetaData = list(Topics = topics))  
105          }          }
106    
107          return(doc)  `[<-.PCorpus` <- function(x, i, value) {
108        db <- filehash::dbInit(DBControl(x)[["dbName"]], DBControl(x)[["dbType"]])
109        counter <- 1
110        for (id in unclass(x)[i]) {
111            if (identical(length(value), 1)) db[[id]] <- value
112            else db[[id]] <- value[[counter]]
113            counter <- counter + 1
114      }      }
115        x
116  }  }
 class(reut21578xml_parser) <- "function_generator"  
117    
118  rcv1_parser <- function(...) {  `[[.PCorpus` <-  function(x, i) {
119      function(elem, lodsupport, load, id) {      db <- filehash::dbInit(DBControl(x)[["dbName"]], DBControl(x)[["dbType"]])
120          corpus <- paste(elem$content, "\n", collapse = "")      filehash::dbFetch(db, NextMethod("[["))
121          tree <- xmlTreeParse(corpus, asText = TRUE)  }
122          node <- xmlRoot(tree)  `[[.VCorpus` <-  function(x, i) {
123        lazyTmMap <- meta(x, tag = "lazyTmMap", type = "corpus")
124        if (!is.null(lazyTmMap))
125            .Call("copyCorpus", x, materialize(x, i))
126        NextMethod("[[")
127    }
128    
129          # Mask as list to bypass S4 checks  `[[<-.PCorpus` <-  function(x, i, value) {
130          class(tree) <- "list"      db <- filehash::dbInit(DBControl(x)[["dbName"]], DBControl(x)[["dbType"]])
131        index <- unclass(x)[[i]]
132        db[[index]] <- value
133        x
134    }
135    `[[<-.VCorpus` <-  function(x, i, value) {
136        # Mark new objects as not active for lazy mapping
137        lazyTmMap <- meta(x, tag = "lazyTmMap", type = "corpus")
138        if (!is.null(lazyTmMap)) {
139            lazyTmMap$index[i] <- FALSE
140            meta(x, tag = "lazyTmMap", type = "corpus") <- lazyTmMap
141        }
142        # Set the value
143        cl <- class(x)
144        y <- NextMethod("[[<-")
145        class(y) <- cl
146        y
147    }
148    
149          datetimestamp <- xmlAttrs(node)[["date"]]  # Update NodeIDs of a CMetaData tree
150          id <- xmlAttrs(node)[["itemid"]]  .update_id <- function(x, id = 0, mapping = NULL, left.mapping = NULL, level = 0) {
151          heading <- xmlValue(node[["title"]])      # Traversal of (binary) CMetaData tree with setup of NodeIDs
152        set_id <- function(x) {
153            x$NodeID <- id
154            id <<- id + 1
155            level <<- level + 1
156            if (length(x$Children) > 0) {
157                mapping <<- cbind(mapping, c(x$Children[[1]]$NodeID, id))
158                left <- set_id(x$Children[[1]])
159                if (level == 1) {
160                    left.mapping <<- mapping
161                    mapping <<- NULL
162                }
163                mapping <<- cbind(mapping, c(x$Children[[2]]$NodeID, id))
164                right <- set_id(x$Children[[2]])
165    
166          if (!lodsupport || (lodsupport && load)) {              x$Children <- list(left, right)
167              doc <- new("XMLTextDocument", .Data = tree, URI = elem$uri, Cached = TRUE, Author = "",          }
168                         DateTimeStamp = datetimestamp, Description = "", ID = id, Origin = "Reuters Corpus Volume 1 XML",          level <<- level - 1
169                         Heading = heading)          x
170          } else {      }
171              doc <- new("XMLTextDocument", URI = elem$uri, Cached = FALSE, Author = "",      list(root = set_id(x), left.mapping = left.mapping, right.mapping = mapping)
                        DateTimeStamp = datetimestamp, Description = "", ID = id, Origin = "Reuters Corpus Volume 1 XML",  
                        Heading = heading)  
172          }          }
173    
174          return(doc)  # Find indices to be updated for a CMetaData tree
175    .find_indices <- function(x) {
176        indices.mapping <- NULL
177        for (m in levels(as.factor(DMetaData(x)$MetaID))) {
178            indices <- (DMetaData(x)$MetaID == m)
179            indices.mapping <- c(indices.mapping, list(m = indices))
180            names(indices.mapping)[length(indices.mapping)] <- m
181      }      }
182        indices.mapping
183  }  }
 class(rcv1_parser) <- "function_generator"  
184    
185  newsgroup_parser <- function(...) {  c2 <- function(x, y, ...) {
186      function(elem, lodsupport, load, id) {      # Update the CMetaData tree
187          mail <- elem$content      cmeta <- .MetaDataNode(0, list(merge_date = as.POSIXlt(Sys.time(), tz = "GMT"), merger = Sys.getenv("LOGNAME")), list(CMetaData(x), CMetaData(y)))
188          author <- gsub("From: ", "", grep("^From:", mail, value = TRUE))      update.struct <- .update_id(cmeta)
         datetimestamp <- gsub("Date: ", "", grep("^Date:", mail, value = TRUE))  
         origin <- gsub("Path: ", "", grep("^Path:", mail, value = TRUE))  
         heading <- gsub("Subject: ", "", grep("^Subject:", mail, value = TRUE))  
         newsgroup <- gsub("Newsgroups: ", "", grep("^Newsgroups:", mail, value = TRUE))  
189    
190          if (!lodsupport || (lodsupport && load)) {      new <- .VCorpus(c(unclass(x), unclass(y)), update.struct$root, NULL)
             # The header is separated from the body by a blank line.  
             # Reference: \url{http://en.wikipedia.org/wiki/E-mail#Internet_e-mail_format}  
             for (index in seq(along = mail)) {  
                 if (mail[index] == "")  
                     break  
             }  
             content <- mail[(index + 1):length(mail)]  
191    
192              doc <- new("NewsgroupDocument", .Data = content, URI = elem$uri, Cached = TRUE,      # Find indices to be updated for the left tree
193                         Author = author, DateTimeStamp = datetimestamp,      indices.mapping <- .find_indices(x)
                        Description = "", ID = id, Origin = origin,  
                        Heading = heading, Newsgroup = newsgroup)  
         } else {  
             doc <- new("NewsgroupDocument", URI = elem$uri, Cached = FALSE, Author = author, DateTimeStamp = datetimestamp,  
                        Description = "", ID = id, Origin = origin, Heading = heading, Newsgroup = newsgroup)  
         }  
194    
195          return(doc)      # Update the DMetaData data frames for the left tree
196      }      for (i in 1:ncol(update.struct$left.mapping)) {
197            map <- update.struct$left.mapping[,i]
198            DMetaData(x)$MetaID <- replace(DMetaData(x)$MetaID, indices.mapping[[as.character(map[1])]], map[2])
199  }  }
 class(newsgroup_parser) <- "function_generator"  
200    
201  # Parse a <newsitem></newsitem> element from a well-formed RCV1 XML file      # Find indices to be updated for the right tree
202  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"]])  
203    
204      new("PlainTextDocument", .Data = corpus, Cached = TRUE, URI = "", Author = "", DateTimeStamp = datetimestamp,      # Update the DMetaData data frames for the right tree
205          Description = "", ID = id, Origin = "Reuters Corpus Volume 1 XML", Heading = heading)      for (i in 1:ncol(update.struct$right.mapping)) {
206            map <- update.struct$right.mapping[,i]
207            DMetaData(y)$MetaID <- replace(DMetaData(y)$MetaID, indices.mapping[[as.character(map[1])]], map[2])
208  }  }
209    
210  # Parse a <REUTERS></REUTERS> element from a well-formed Reuters-21578 XML file      # Merge the DMetaData data frames
211  reut21578xml_to_plain <- function(node, ...) {      labels <- setdiff(names(DMetaData(y)), names(DMetaData(x)))
212      # 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))
213      if (!is.null(node[["TEXT"]][["AUTHOR"]]))      x.dmeta.aug <- cbind(DMetaData(x), na.matrix)
214          author <- xmlValue(node[["TEXT"]][["AUTHOR"]])      labels <- setdiff(names(DMetaData(x)), names(DMetaData(y)))
215      else      na.matrix <- matrix(NA, nrow = nrow(DMetaData(y)), ncol = length(labels), dimnames = list(row.names(DMetaData(y)), labels))
216          author <- ""      y.dmeta.aug <- cbind(DMetaData(y), na.matrix)
217        DMetaData(new) <- rbind(x.dmeta.aug, y.dmeta.aug)
218    
219      datetimestamp <- xmlValue(node[["DATE"]])      new
220      description <- ""  }
     id <- xmlAttrs(node)[["NEWID"]]  
221    
222      origin <- "Reuters-21578 XML"  c.Corpus <-
223    function(x, ..., recursive = FALSE)
224    {
225        args <- list(...)
226    
227      # The <BODY></BODY> tag is unfortunately NOT obligatory!      if (identical(length(args), 0))
228      if (!is.null(node[["TEXT"]][["BODY"]]))          return(x)
         corpus <- xmlValue(node[["TEXT"]][["BODY"]])  
     else  
         corpus <- ""  
229    
230      # The <TITLE></TITLE> tag is unfortunately NOT obligatory!      if (!all(unlist(lapply(args, inherits, class(x)))))
231      if (!is.null(node[["TEXT"]][["TITLE"]]))          stop("not all arguments are of the same corpus type")
         heading <- xmlValue(node[["TEXT"]][["TITLE"]])  
     else  
         heading <- ""  
232    
233      topics <- unlist(xmlApply(node[["TOPICS"]], function(x) xmlValue(x)), use.names = FALSE)      if (inherits(x, "PCorpus"))
234            stop("concatenation of corpora with underlying databases is not supported")
235    
236      new("PlainTextDocument", .Data = corpus, Cached = TRUE, URI = "", Author = author, DateTimeStamp = datetimestamp,      Reduce(c2, base::c(list(x), args))
         Description = description, ID = id, Origin = origin, Heading = heading, LocalMetaData = list(Topics = topics))  
237  }  }
238    
239  setGeneric("load_doc", function(object, ...) standardGeneric("load_doc"))  c.TextDocument <- function(x, ..., recursive = FALSE) {
 setMethod("load_doc",  
           signature(object = "PlainTextDocument"),  
           function(object, ...) {  
               if (!Cached(object)) {  
                   con <- eval(parse(text = URI(object)))  
                   corpus <- readLines(con)  
                   close(con)  
                   Corpus(object) <- corpus  
                   Cached(object) <- TRUE  
                   return(object)  
               } else {  
                   return(object)  
               }  
           })  
 setMethod("load_doc",  
           signature(object =  "XMLTextDocument"),  
           function(object, ...) {  
               if (!Cached(object)) {  
                   con <- eval(parse(text = URI(object)))  
                   corpus <- paste(readLines(con), "\n", collapse = "")  
                   close(con)  
                   doc <- xmlTreeParse(corpus, asText = TRUE)  
                   class(doc) <- "list"  
                   Corpus(object) <- doc  
                   Cached(object) <- TRUE  
                   return(object)  
               } else {  
                   return(object)  
               }  
           })  
 setMethod("load_doc",  
           signature(object = "NewsgroupDocument"),  
           function(object, ...) {  
               if (!Cached(object)) {  
                   con <- eval(parse(text = URI(object)))  
                   mail <- readLines(con)  
                   close(con)  
                   Cached(object) <- TRUE  
                   for (index in seq(along = mail)) {  
                       if (mail[index] == "")  
                           break  
                   }  
                   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("as.plaintext_doc", function(object, FUN, ...) standardGeneric("as.plaintext_doc"))  
 setMethod("as.plaintext_doc",  
           signature(object = "PlainTextDocument"),  
           function(object, FUN, ...) {  
               return(object)  
           })  
 setMethod("as.plaintext_doc",  
           signature(object = "XMLTextDocument", FUN = "function"),  
           function(object, FUN, ...) {  
               if (!Cached(object))  
                   object <- load_doc(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("stem_doc", function(object, ...) standardGeneric("stem_doc"))  
 setMethod("stem_doc",  
           signature(object = "PlainTextDocument"),  
           function(object, ...) {  
               if (!Cached(object))  
                   object <- load_doc(object)  
   
               require(Rstem)  
               splittedCorpus <- unlist(strsplit(object, " ", fixed = TRUE))  
               stemmedCorpus <- wordStem(splittedCorpus, ...)  
               Corpus(object) <- paste(stemmedCorpus, collapse = " ")  
               return(object)  
           })  
   
 setGeneric("remove_words", function(object, stopwords, ...) standardGeneric("remove_words"))  
 setMethod("remove_words",  
           signature(object = "PlainTextDocument", stopwords = "character"),  
           function(object, stopwords, ...) {  
               if (!Cached(object))  
                   object <- load_doc(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 <- load_doc(object)  
   
               return(any(grep(pattern, Corpus(object))))  
           })  
   
 setGeneric("attach_data", function(object, data) standardGeneric("attach_data"))  
 setMethod("attach_data",  
           signature(object = "TextDocCol", data = "TextDocument"),  
           function(object, data) {  
               data <- as(list(data), "TextDocCol")  
               object@.Data <- as(c(object@.Data, data), "TextDocCol")  
               return(object)  
           })  
   
 setGeneric("attach_metadata", function(object, name, metadata) standardGeneric("attach_metadata"))  
 setMethod("attach_metadata",  
           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("set_subscriptable", function(object, name) standardGeneric("set_subscriptable"))  
 setMethod("set_subscriptable",  
           signature(object = "TextDocCol"),  
           function(object, name) {  
               if (!is.character(GlobalMetaData(object)$subscriptable))  
                   object <- attach_metadata(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)  
   
               object <- x  
               object@.Data <- x@.Data[i, ..., drop = FALSE]  
               for (m in names(GlobalMetaData(object))) {  
                   if (m %in% GlobalMetaData(object)$subscriptable) {  
                       object@GlobalMetaData[[m]] <- GlobalMetaData(object)[[m]][i, ..., drop = FALSE]  
                   }  
               }  
               return(object)  
           })  
   
 setMethod("[<-",  
           signature(x = "TextDocCol", i = "ANY", j = "ANY", value = "ANY"),  
           function(x, i, j, ... , value) {  
               object <- x  
               object@.Data[i, ...] <- value  
               return(object)  
           })  
   
 setMethod("[[",  
           signature(x = "TextDocCol", i = "ANY", j = "ANY"),  
           function(x, i, j, ...) {  
               return(x@.Data[[i, ...]])  
           })  
   
 setMethod("[[<-",  
           signature(x = "TextDocCol", i = "ANY", j = "ANY", value = "ANY"),  
           function(x, i, j, ..., value) {  
               object <- x  
               object@.Data[[i, ...]] <- value  
               return(object)  
           })  
   
 setMethod("c",  
           signature(x = "TextDocCol"),  
           function(x, ..., recursive = TRUE){  
240                args <- list(...)                args <- list(...)
241                if(length(args) == 0)  
242                    return(x)      if (identical(length(args), 0))
               return(as(c(as(x, "list"), ...), "TextDocCol"))  
     })  
 setMethod("c",  
           signature(x = "TextDocument"),  
           function(x, ..., recursive = TRUE){  
               args <- list(...)  
               if(length(args) == 0)  
243                    return(x)                    return(x)
               return(new("TextDocCol", .Data = list(x, ...)))  
     })  
244    
245  setMethod("length",      if (!all(unlist(lapply(args, inherits, class(x)))))
246            signature(x = "TextDocCol"),          stop("not all arguments are text documents")
           function(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)  
                   cat("\n")  
               else  
                   cat("s\n")  
     })  
247    
248  setMethod("summary",      dmeta <- data.frame(MetaID = rep(0, length(list(x, ...))), stringsAsFactors = FALSE)
249            signature(object = "TextDocCol"),      .VCorpus(list(x, ...), .MetaDataNode(), dmeta)
250            function(object){  }
251                show(object)  
252                if (length(GlobalMetaData(object)) > 0) {  print.Corpus <- function(x, ...) {
253                    cat("\nThe global metadata consists of", length(GlobalMetaData(object)), "tag-value pair")      cat(sprintf(ngettext(length(x),
254                    if (length(GlobalMetaData(object)) == 1)                           "A corpus with %d text document\n",
255                        cat(".\n")                           "A corpus with %d text documents\n"),
256                    else                  length(x)))
257                        cat("s.\n")      invisible(x)
258    }
259    
260    summary.Corpus <- function(object, ...) {
261        print(object)
262        if (length(DMetaData(object)) > 0) {
263            cat(sprintf(ngettext(length(attr(CMetaData(object), "MetaData")),
264                                 "\nThe metadata consists of %d tag-value pair and a data frame\n",
265                                 "\nThe metadata consists of %d tag-value pairs and a data frame\n"),
266                        length(CMetaData(object)$MetaData)))
267                    cat("Available tags are:\n")                    cat("Available tags are:\n")
268                    cat(names(GlobalMetaData(object)), "\n")          cat(strwrap(paste(names(CMetaData(object)$MetaData), collapse = " "), indent = 2, exdent = 2), "\n")
269            cat("Available variables in the data frame are:\n")
270            cat(strwrap(paste(names(DMetaData(object)), collapse = " "), indent = 2, exdent = 2), "\n")
271        }
272                }                }
     })  
273    
274  setGeneric("inspect", function(object) standardGeneric("inspect"))  inspect <- function(x) UseMethod("inspect", x)
275  setMethod("inspect",  inspect.PCorpus <- function(x) {
276            signature("TextDocCol"),      summary(x)
277            function(object) {      cat("\n")
278                summary(object)      db <- filehash::dbInit(DBControl(x)[["dbName"]], DBControl(x)[["dbType"]])
279        show(filehash::dbMultiFetch(db, unlist(x)))
280    }
281    inspect.VCorpus <- function(x) {
282        summary(x)
283                cat("\n")                cat("\n")
284                show(as(object, "list"))      print(noquote(lapply(x, identity)))
285            })  }
286    
287  # No metadata is checked  lapply.PCorpus <- function(X, FUN, ...) {
288  setGeneric("%IN%", function(x, y) standardGeneric("%IN%"))      db <- filehash::dbInit(DBControl(X)[["dbName"]], DBControl(X)[["dbType"]])
289  setMethod("%IN%",      lapply(filehash::dbMultiFetch(db, unlist(X)), FUN, ...)
290            signature(x = "TextDocument", y = "TextDocCol"),  }
291            function(x, y) {  lapply.VCorpus <- function(X, FUN, ...) {
292                x %in% y      lazyTmMap <- meta(X, tag = "lazyTmMap", type = "corpus")
293            })      if (!is.null(lazyTmMap))
294            .Call("copyCorpus", X, materialize(X))
295        base::lapply(X, FUN, ...)
296    }
297    
298    writeCorpus <-  function(x, path = ".", filenames = NULL) {
299        filenames <- file.path(path,
300                               if (is.null(filenames)) unlist(lapply(x, function(x) sprintf("%s.txt", ID(x))))
301                               else filenames)
302        i <- 1
303        for (o in x) {
304            writeLines(as.PlainTextDocument(o), filenames[i])
305            i <- i + 1
306        }
307    }

Legend:
Removed from v.66  
changed lines
  Added in v.1021

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