正则表达式模式匹配一​​个字符

时间:2010-08-20 03:50:47

标签: r string

我是R的新手,所以如果这很简单直截了当,我道歉。我已成功将网页读入字符向量。我想将此字符串拆分为较小的段,以便我可以提取一些数据。到目前为止,这很容易。

问题是我是regex和R的新手,所以这对我来说非常困难。我只是想缩短字符串,使其包含

之间的所有内容
<div class="appForm"

and 

</div>

出于某种原因,我很难使用stringr包和?str_match。

任何帮助 - 更有效的解决方案 - 都将非常感激。网络抓取的新手,但决定留在R。

3 个答案:

答案 0 :(得分:5)

社区中的一些人heavily discourage使用正则表达式来解析包含任意数量的嵌套表达式的文本。 R确实有XML parser(也适用于HTML),您可以考虑将其用于此目的。

答案 1 :(得分:3)

我建议使用XML包和XPath。这需要一些学习,但如果你认真对待网络抓取,那就是要走的路。我用很久以前的纽约时报网站的一些县级选举数据做了这个,代码看起来像这样(只是为了给你一个想法):

getCounty <- function(url) {
    doc = htmlTreeParse(url, useInternalNodes = TRUE)

    nodes <- getNodeSet(doc, "//tr/td[@class='county-name']/text()")
    tmp <- sapply(nodes, xmlValue)
    county <- sapply(tmp, function(x) clean(x, num=FALSE))

    return(county)
}

您可以了解XPath here

另一个例子:从Crantastic时间线中获取所有R包名称。这将查找具有div“时间轴”的id节点,然后查找具有“时间轴”类的ul,并从中提取所有第一个a节点父节点,并返回其文本:

url <- 'http://crantastic.org/'
doc = htmlTreeParse(url, useInternalNodes = TRUE)

nodes <- getNodeSet(doc, "//div[@id='timeline']/ul[@class='timeline']/li/a[1]/text()")
tmp <- sapply(nodes, xmlValue)
tmp

>  [1] "landis"          "vegan"           "mutossGUI"       "lordif"         
 [5] "futile.paradigm" "lme4"            "tm"              "qpcR"           
 [9] "igraph"          "aspace"          "ade4"            "MCMCglmm"       
[13] "hts"             "emdbook"         "DCGL"            "wq"             
[17] "crantastic"      "Psychometrics"   "crantastic"      "gR"             
[21] "crantastic"      "Distributions"   "rAverage"        "spikeslab"      
[25] "sem"

答案 2 :(得分:2)

我第二个Stephen和Vince建议使用htmlTreeParse包中的XML。基于这个想法,在R中抓取/使用HTML内容有很多与SO有关的问题。看看

Scraping html tables into R data frames using the XML package

How can I use R (Rcurl/XML packages ?!) to scrape this webpage ?

How to isolate a single element from a scraped web page in R

How to transform XML data into a data.frame?