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

Legend:
Removed from v.63  
changed lines
  Added in v.1114

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