【发布时间】:2015-03-31 05:55:40
【问题描述】:
我需要(非手动)下载此文件并将内容转换为 data.frame,忽略几行的能力会很有用。 我正在专门寻找 R 或 Python 中的解决方案。
文件本身可以取自:
http://horizons.prod.transmissionmedia.ca/GetDailyFundSummaryExcel.aspx?lang=en
这是我到目前为止所做的:
- 我试过 XLConnect (
Error: IllegalArgumentException (Java): Your InputStream was neither an OLE2 stream, nor an OOXML stream) - 我试过 RODBC (
Error in odbcConnectExcel("xl.file") : odbcConnectExcel is only usable with 32-bit Windows) - 我在 Python 中尝试过 xlrd (
XLRDError: Unsupported format or corrupt file) - 我试过 gdata (
Error in xls2sep(xls, sheet, verbose = verbose, ..., method = method, : Intermediate file '...' missing!)
如果您在记事本中打开该文件,它是一个 xml 文件,在 Excel 中打开时,您会收到一条警告消息“格式和扩展名不匹配”。
我可以自己探索的想法也很有用,如果您没有答案,请发表评论。
到目前为止我对 XML/regex 的尝试:
library(XML)
library(stringr)
download.file("http://horizons.prod.transmissionmedia.ca/GetDailyFundSummaryExcel.aspx?lang=en", destfile = "horizons.xls")
doc <- readLines(con = "horizons.xls")
doc <- str_extract(doc,"<Table[^>]*>(.*?)</Table>")
doc <- xmlParse(doc)
listing <- xpathApply(doc, "//Row", xmlToDataFrame)
listing <- listing[4:length(listing)]
listing <- do.call(rbind,lapply(listing, t))[,6:16]
listing[,3:11] <- gsub("[^-.0-9]", "", listing[,3:11])
listing <- as.data.frame(listing, row.names = NULL,stringsAsFactors = FALSE,)
listing$V1 <- str_replace_all(listing$V1, "[^a-zA-Z0-9]", " ")
listing[5:11] <- lapply(listing[5:11],as.numeric)
names(listing) <- c(
"Product Name",
"Ticker",
"Class",
"Price",
"Price % Change",
"Volume",
"NAV/unit",
"NAV % Change",
"% Prem/Disc",
"Outst. Shares"
)
【问题讨论】:
-
试试 read.xls r-bloggers.com/read-excel-files-from-r
-
第一:不要在 Internet Explorer 中下载文件,因为 *在某些版本中“它会不必要地将文件扩展名从 .xls 更改为 .xml。
-
第二:有没有考虑自己解析XML?
-
@Steve 使用 R XML 包下载文件。不是手工做的。
-
@Steve XML 对我来说仍然很神秘。我没有考虑过。