我必须每周处理数百万个xml文件,并使用具有32个核心的服务器。我在Ubuntu 14.04上运行R.我当前的程序使用这些文件中的for循环提取数据并将输出保存到MySQL。由于处理速度很慢,我尝试并行解析xml中的数据。以下是我目前的代码:
//Function to parse data from xml
parse_xml <-function(FileName) {
xmldata <- xmlParse(FileName)
result_nodes = XML::getNodeSet(xmldata , "//IOTModellerLog/Event")
if (!length(result_nodes)==0){
abc <- rbindlist(lapply(result_nodes,function(x) data.frame(as.list(unlist(xmlToList(x))))),use.names = TRUE, fill = TRUE)
....do other calculations....
abc <- data.frame(lapply(abc, as.character), stringsAsFactors = FALSE)
}
}
//合并两个数据帧的函数,其中NA填充非匹配列
sbind = function(x, y, fill=NA) {
sbind.fill = function(d, cols){
for(c in cols)
d[[c]] = fill
d
}
x = sbind.fill(x, setdiff(names(y),names(x)))
y = sbind.fill(y, setdiff(names(x),names(y)))
rbind(x, y)
}
所有xml文件的路径
path <- "/home/mycomp/Documents/xmls/xmlfrommtar"
parsexml的功能。
workerFunc <- function(file) {
dat <- parse_xml(file)
df <- sbind(df,dat)
}
并行处理代码
cl <- makeCluster(detectCores())
files <- dir(path, pattern="*.xml|*.XML", full.names = T)
part <- clusterSplit(cl, seq_along(files))
filesPart <- lapply(part, function(p) files[p])
results <- clusterApply(cl, filesPart, workerFunc)
当我运行它时,我收到以下错误:
Error in checkForRemoteErrors(val) :
4 nodes produced errors; first error: could not find function "parse_xml"
这表明我有两件事,文件分布在我机器的所有4个核心上。函数clusterApply无法在workerFunc
内找到parse_xml。但是,我的环境中几乎有parse_xml文件。
示例XML数据
IOTModellerLog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" DeviceID="7430180" ClientID="12324" FileCreationDate="2017-03-01T22:40:03" FileVersion="2" EventClassID="65535" IOTLogCreationDate="2017-03-01T12:29:54" SampleID="1" xsi:noNamespaceSchemaLocation="/opt/nds/ams_proxy/webapps/ams_proxy/WEB-INF/amsXmlSchema.xsd">
<Event EventTime="2017-02-27T18:33:58">
<IOTEvent State="PowerOn" />
</Event>
<Event EventTime="2017-02-28T08:59:03">
<DataEvent>
<Model>1</Model>
<DataType>1</DataType>
<DataValue>0301</DataValue>
</DataEvent>
</Event>
<Event EventTime="2017-02-28T08:59:13">
<DataEvent>
<Model>1</Model>
<DataType>1</DataType>
<DataValue>0401</DataValue>
</DataEvent>
</Event>
</IOTModellerLog>
答案 0 :(得分:0)
您应该使用以下内容初始化集群工作者:
__doc__