7

我正在使用该xml2包将一个巨大的 XML 文件读入内存,但该命令失败并出现以下错误:

错误:字符 0x0 超出允许范围 [9]

我的代码如下所示:

library(xml2)
doc <- read_xml('~/Downloads/FBrf.xml')

数据可以在ftp://ftp.flybase.net/releases/FB2015_05/reporting-xml/FBrf.xml.gz 下载(大约 140MB),解压后大约有 1.8GB。

有没有人建议如何在阅读之前找出哪些字符有问题或如何清理文件。

编辑

好的,因为文件很大,所以我搜索了有关堆栈溢出的其他解决方案,并尝试实现 Martin Morgan 的解决方案,他在这里介绍了将值合并到巨大的 XML 文件中

所以到目前为止我所做的是以下代码行

library(XML)
branchFunction <- function(progress=10) {
    res <- new.env(parent=emptyenv())   # for results
    it <- 0L                            # iterator -- nodes visited
    list(publication=function(elt) {
        ## handle 'publication' nodes 
        if (getNodeSet(elt, "not(/publication/feature/id)"))
            ## early exit -- no feature id
            return(NULL)
        it <<- it + 1L
        if (it %% progress == 0L)
            message(it)
        publication <- getNodeSet(elt, "string(/publication/id/text())") # 'key'
        res[[publication]] <-
            list(miniref=getNodeSet(elt,
                   "normalize-space(/publication/miniref/text())"),
                 features= xpathSApply(elt, "//feature/id/text()", xmlValue))
    }, getres = function() {
        ## retrieve the 'res' environment when done
        res
    }, get=function() {
        ## retrieve 'res' environment as data.frame
        publication <- ls(res)
        miniref <- unlist(eapply(res, "[[", "miniref"), use.names=FALSE)
        feature <- eapply(res, "[[", "features")
        len <- sapply(feature, length)
        data.frame(publication=rep(publication, len),
                   feature=unlist(feature, use.names=FALSE), 
                   miniref=rep(miniref, len))
    })
}

branches <- branchFunction()
xmlEventParse("~/Downloads/jnk.xml", handlers=NULL, branches=branches)
# xmlEventParse("~/Downloads/FBrf.xml", handlers=NULL, branches=branches)
branches$get()

我将 xml 文件上传到我的服务器http://download.dejung.net/jnk.xml

该文件只有几 kb,但问题是结果。第二个发布条目有一个 id FBrf0162243和一个 miniref Schwartz et al., 2003, Mol. Cell. Biol. 23(19): 6876--6886

我上面发布的代码的结果向相应的 miniref 报告了错误的发布 ID。特征ID是正确的......

FBrf0050934 FBgn0003277 Schwartz 等人,2003 年,摩尔。细胞。生物学。23(19): 6876--6886

不知道为什么我的代码报告了错误的值,也许有人可以帮助我关闭闭包,因为这对我来说很新。

4

2 回答 2

1

在命令行中,我iconv -f utf-8 -t utf-8 FBrf.xml > outfile.xml 对您的文件运行了命令。它使肉眼可见,但我没有安装 R 来测试它。

(如果在 Windows 上,您需要安装 cygwin 才能访问 iconv)

于 2016-02-05T14:00:49.540 回答
1

我偶尔会遇到可能与此类似的“embedded NULL”错误消息(如果0x0此消息中的 表示相同的NULL问题)。我的方法是在读取文件之前尝试删除它们,因为我还没有找到忽略它们的 R 包。

如果您在 Unix 或 OS X 上,您可以通过以下方式sed在您的 R 程序中调用:

system( 'sed "s/\\0//g" ~/Downloads/dirty.xml > ~/Downloads/clean.xml' )

如果这不起作用,您可能需要扩展这个字符“黑名单”——例如参见Unicode Regex;无效的 XML 字符

如果仍然有问题,那么有时我会创建一个字符白名单——删除所有不在指定字符集中的内容..

sed 's/[^A-Za-z0-9 _.,"]//g' ~/Downloads/dirty.csv > ~/Downloads/clean.csv

这是我用于 .csv 数据文件的文件(不关心</etc.>),因此您可能希望将其扩展为[^[:ascii:]]

如果您在 Windows 上,您可能不得不在 R 之外使用这种方法——例如,您可以使用 Cygwin 而不是system()上面的调用。

于 2016-02-05T13:40:13.020 回答