R:从网站中提取单词

R:从网站中提取单词,r,regex,rvest,R,Regex,Rvest,我正在尝试从网站中提取以特定短语开头的所有单词。我使用的网站是: 我想提取所有以stat开头的单词。我应该得到21个像stat_identity这样的名字作为回报。我有以下代码: stats <- readLines("http://docs.ggplot2.org/current/") head(stats) grep("stat_{1[a-z]", stats, value=TRUE) 我想我得到的输出是一个空字符串,其中有一个stat_uuu短语?所以现在我想办法提取所有文

我正在尝试从网站中提取以特定短语开头的所有单词。我使用的网站是:

我想提取所有以stat开头的单词。我应该得到21个像stat_identity这样的名字作为回报。我有以下代码:

 stats <- readLines("http://docs.ggplot2.org/current/")
 head(stats)

 grep("stat_{1[a-z]", stats, value=TRUE)
我想我得到的输出是一个空字符串,其中有一个stat_uuu短语?所以现在我想办法提取所有文本,并将所有非统计短语设置为空字符串。有人对如何获得我想要的输出有什么想法吗?

rvest&stringr救援:

library(xml2)
library(rvest)
library(stringr)

pg <- read_html("http://docs.ggplot2.org/current/")

unique(str_match_all(html_text(html_nodes(pg, "body")),
                     "(stat_[[:alnum:]_]+)")[[1]][,2])
##  [1] "stat_bin"                 "stat_bin2dCount"         
##  [3] "stat_bindot"              "stat_binhexBin"          
##  [5] "stat_boxplot"             "stat_contour"            
##  [7] "stat_density"             "stat_density2d"          
##  [9] "stat_ecdf"                "stat_functionSuperimpose"
## [11] "stat_identity"            "stat_qqCalculation"      
## [13] "stat_quantile"            "stat_smooth"             
## [15] "stat_spokeConvert"        "stat_sum"                
## [17] "stat_summarySummarise"    "stat_summary_hexApply"   
## [19] "stat_summary2dApply"      "stat_uniqueRemove"       
## [21] "stat_ydensity"            "stat_defaults"

除非您需要链接,否则您可以使用其他rvest功能,这将为您删除所有标记,并只为您提供网站文本。

旁注:rvest的0.3.0版会自动加载程序包xml2.aye,但我希望避免加载所需的程序包…只要有可能,消息hrbrmstr和Pascal,你们都是救生员!非常感谢您了解R!:
library(xml2)
library(rvest)
library(stringr)

pg <- read_html("http://docs.ggplot2.org/current/")

unique(str_match_all(html_text(html_nodes(pg, "body")),
                     "(stat_[[:alnum:]_]+)")[[1]][,2])
##  [1] "stat_bin"                 "stat_bin2dCount"         
##  [3] "stat_bindot"              "stat_binhexBin"          
##  [5] "stat_boxplot"             "stat_contour"            
##  [7] "stat_density"             "stat_density2d"          
##  [9] "stat_ecdf"                "stat_functionSuperimpose"
## [11] "stat_identity"            "stat_qqCalculation"      
## [13] "stat_quantile"            "stat_smooth"             
## [15] "stat_spokeConvert"        "stat_sum"                
## [17] "stat_summarySummarise"    "stat_summary_hexApply"   
## [19] "stat_summary2dApply"      "stat_uniqueRemove"       
## [21] "stat_ydensity"            "stat_defaults"