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/trunk/R/textdoccol.R revision 21, Sat Nov 19 10:23:19 2005 UTC pkg/R/corpus.R revision 1419, Sat May 2 17:23:47 2015 UTC
# Line 1  Line 1 
1  # Author: Ingo Feinerer  # Author: Ingo Feinerer
2    
3  # S4 class definition  PCorpus <-
4  # Text document collection  function(x,
5  setClass("textdoccol",           readerControl = list(reader = reader(x), language = "en"),
6           representation(tdm = "termdocmatrix"),           dbControl = list(dbName = "", dbType = "DB1"))
7           contains = c("list"))  {
8        stopifnot(inherits(x, "Source"))
9  # Accessor functions as described in "S4 Classes in 15 pages, more or less"  
10        readerControl <- prepareReader(readerControl, reader(x))
11  if (!isGeneric("tdm")) {  
12      if (is.function("tdm"))      if (!filehash::dbCreate(dbControl$dbName, dbControl$dbType))
13          fun <- tdm          stop("error in creating database")
14        db <- filehash::dbInit(dbControl$dbName, dbControl$dbType)
15    
16        x <- open(x)
17        tdl <- vector("list", length(x))
18        counter <- 1
19        while (!eoi(x)) {
20            x <- stepNext(x)
21            elem <- getElem(x)
22            doc <- readerControl$reader(elem,
23                                        readerControl$language,
24                                        as.character(counter))
25            filehash::dbInsert(db, meta(doc, "id"), doc)
26            tdl[[counter]] <- meta(doc, "id")
27            counter <- counter + 1
28        }
29        x <- close(x)
30    
31        p <- list(content = tdl,
32                  meta = CorpusMeta(),
33                  dmeta = data.frame(row.names = seq_along(tdl)),
34                  dbcontrol = dbControl)
35        class(p) <- c("PCorpus", "Corpus")
36        p
37    }
38    
39    Corpus <-
40    VCorpus <-
41    function(x, readerControl = list(reader = reader(x), language = "en"))
42    {
43        stopifnot(inherits(x, "Source"))
44    
45        readerControl <- prepareReader(readerControl, reader(x))
46    
47        x <- open(x)
48        tdl <- vector("list", length(x))
49        # Check for parallel element access
50        if (is.function(getS3method("pGetElem", class(x), TRUE)))
51            tdl <- mapply(function(elem, id)
52                              readerControl$reader(elem, readerControl$language, id),
53                          pGetElem(x),
54                          id = as.character(seq_along(x)),
55                          SIMPLIFY = FALSE)
56        else {
57            counter <- 1
58            while (!eoi(x)) {
59                x <- stepNext(x)
60                elem <- getElem(x)
61                doc <- readerControl$reader(elem,
62                                            readerControl$language,
63                                            as.character(counter))
64                tdl[[counter]] <- doc
65                counter <- counter + 1
66            }
67        }
68        x <- close(x)
69    
70        as.VCorpus(tdl)
71    }
72    
73    `[.PCorpus` <-
74    function(x, i)
75    {
76        if (!missing(i)) {
77            x$content <- x$content[i]
78            x$dmeta <- x$dmeta[i, , drop = FALSE]
79        }
80        x
81    }
82    
83    `[.VCorpus` <-
84    function(x, i)
85    {
86        if (!missing(i)) {
87            x$content <- x$content[i]
88            x$dmeta <- x$dmeta[i, , drop = FALSE]
89            if (!is.null(x$lazy))
90                x$lazy$index <- x$lazy$index[i]
91        }
92        x
93    }
94    
95    .map_name_index <-
96    function(x, i)
97    {
98        if (is.character(i))
99            match(i, meta(x, "id", "local"))
100      else      else
101          fun <- function(object) standardGeneric("tdm")          i
102      setGeneric("tdm", fun)  }
103    
104    `[[.PCorpus` <-
105    function(x, i)
106    {
107        i <- .map_name_index(x, i)
108        db <- filehash::dbInit(x$dbcontrol[["dbName"]], x$dbcontrol[["dbType"]])
109        filehash::dbFetch(db, x$content[[i]])
110    }
111    `[[.VCorpus` <-
112    function(x, i)
113    {
114        i <- .map_name_index(x, i)
115        if (!is.null(x$lazy))
116            .Call(copyCorpus, x, materialize(x, i))
117        x$content[[i]]
118    }
119    
120    `[[<-.PCorpus` <-
121    function(x, i, value)
122    {
123        i <- .map_name_index(x, i)
124        db <- filehash::dbInit(x$dbcontrol[["dbName"]], x$dbcontrol[["dbType"]])
125        db[[x$content[[i]]]] <- value
126        x
127    }
128    `[[<-.VCorpus` <-
129    function(x, i, value)
130    {
131        i <- .map_name_index(x, i)
132        # Mark new objects as inactive for lazy mapping
133        if (!is.null(x$lazy))
134            x$lazy$index[i] <- FALSE
135        x$content[[i]] <- value
136        x
137    }
138    
139    as.list.PCorpus <- as.list.VCorpus <-
140    function(x, ...)
141        setNames(content(x), as.character(lapply(content(x), meta, "id")))
142    
143    as.VCorpus <-
144    function(x)
145        UseMethod("as.VCorpus")
146    as.VCorpus.VCorpus <- identity
147    as.VCorpus.list <-
148    function(x)
149    {
150        v <- list(content = x,
151                  meta = CorpusMeta(),
152                  dmeta = data.frame(row.names = seq_along(x)))
153        class(v) <- c("VCorpus", "Corpus")
154        v
155    }
156    
157    outer_union <-
158    function(x, y, ...)
159    {
160        if (nrow(x) > 0L)
161            x[, setdiff(names(y), names(x))] <- NA
162        if (nrow(y) > 0L)
163            y[, setdiff(names(x), names(y))] <- NA
164        res <- rbind(x, y)
165        if (ncol(res) == 0L)
166            res <- data.frame(row.names = seq_len(nrow(x) + nrow(y)))
167        res
168    }
169    
170    c.VCorpus <-
171    function(..., recursive = FALSE)
172    {
173        args <- list(...)
174        x <- args[[1L]]
175    
176        if (length(args) == 1L)
177            return(x)
178    
179        if (!all(unlist(lapply(args, inherits, class(x)))))
180            stop("not all arguments are of the same corpus type")
181    
182        v <- list(content = do.call("c", lapply(args, content)),
183                  meta = CorpusMeta(meta = do.call("c",
184                    lapply(args, function(a) meta(a, type = "corpus")))),
185                  dmeta = Reduce(outer_union, lapply(args, meta)))
186        class(v) <- c("VCorpus", "Corpus")
187        v
188    }
189    
190    content.VCorpus <-
191    function(x)
192    {
193        if (!is.null(x$lazy))
194            .Call(copyCorpus, x, materialize(x))
195        x$content
196    }
197    
198    content.PCorpus <-
199    function(x)
200    {
201        db <- filehash::dbInit(x$dbcontrol[["dbName"]], x$dbcontrol[["dbType"]])
202        filehash::dbMultiFetch(db, unlist(x$content))
203    }
204    
205    inspect <-
206    function(x)
207        UseMethod("inspect", x)
208    inspect.PCorpus <- inspect.VCorpus <-
209    function(x)
210    {
211        print(x)
212        cat("\n")
213        print(noquote(content(x)))
214        invisible(x)
215    }
216    
217    length.PCorpus <- length.VCorpus <-
218    function(x)
219        length(x$content)
220    
221    names.PCorpus <- names.VCorpus <-
222    function(x)
223        as.character(meta(x, "id", "local"))
224    
225    `names<-.PCorpus` <- `names<-.VCorpus` <-
226    function(x, value)
227    {
228        meta(x, "id", "local") <- as.character(value)
229        x
230    }
231    
232    format.PCorpus <- format.VCorpus <-
233    function(x, ...)
234    {
235        c(sprintf("<<%s>>", class(x)[1L]),
236          sprintf("Metadata:  corpus specific: %d, document level (indexed): %d",
237                  length(meta(x, type = "corpus")),
238                  ncol(meta(x, type = "indexed"))),
239          sprintf("Content:  documents: %d", length(x)))
240  }  }
 setMethod("tdm", "textdoccol", function(object) object@tdm)  
241    
242  # Constructors  writeCorpus <-
243    function(x, path = ".", filenames = NULL)
244    {
245        filenames <- file.path(path,
246          if (is.null(filenames))
247              sprintf("%s.txt", as.character(meta(x, "id", "local")))
248          else filenames)
249    
250  setGeneric("textdoccol", function(object, ...) standardGeneric("textdoccol"))      stopifnot(length(x) == length(filenames))
 # Read in text documents in XML Reuters Corpus Volume 1 (RCV1) format  
 setMethod("textdoccol",  
           c("character", "logical", "logical",  "character", "logical", "character", "integer", "integer", "logical"),  
           function(object, stripWhiteSpace = FALSE, toLower = FALSE, weighting = "tf", stemming = FALSE,  
                    language = "german", minWordLength = 3, minDocFreq = 1, stopwords = NULL) {  
               require(XML)  
   
               tree <- xmlTreeParse(object)  
               tdcl <- new("textdoccol", .Data = xmlApply(xmlRoot(tree), parseNewsItem, stripWhiteSpace, toLower))  
               tdcl@tdm = termdocmatrix(tdcl, weighting, stemming, language, minWordLength, minDocFreq, stopwords)  
   
               tdcl  
           })  
   
 # TODO: Implement lacking fields.  
 # For this we need the full RCV1 XML set to know where to find those things  
 parseNewsItem <- function(node, stripWhiteSpace = FALSE, toLower = FALSE) {  
     author <- "Not yet implemented"  
     timestamp <- xmlAttrs(node)[["date"]]  
     description <- "Not yet implemented"  
     id <- as.integer(xmlAttrs(node)[["itemid"]])  
     origin <- "Not yet implemented"  
     corpus <- unlist(xmlApply(node[["text"]], xmlValue), use.names = FALSE)  
   
     if (stripWhiteSpace)  
         corpus <- gsub("[[:space:]]+", " ", corpus)  
     if (toLower)  
         corpus <- tolower(corpus)  
251    
252      heading <- xmlValue(node[["title"]])      mapply(function(doc, f) writeLines(as.character(doc), f), x, filenames)
253    
254      new("textdocument", .Data = corpus, author = author, timestamp = timestamp,      invisible(x)
         description = description, id = id, origin = origin, heading = heading)  
255  }  }

Legend:
Removed from v.21  
changed lines
  Added in v.1419

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