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

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