我在使用stringr
库命名类的字符向量中提取某些匹配项时遇到麻烦:
classes = read_lines("https://statistics.ucdavis.edu/courses/descriptions-undergrad") %>%
str_flatten()
classes
的一小段:
...collaborative data analysis; complete case study review and team data analysis project.
Effective: 2019 Fall Quarter.</p><h2>STA 190X—Seminar (1-2)</h2><p>Seminar—1-2 hour(s). Prerequisite(s):
STA 013 or STA 013Y or STA 032 or STA 100 or STA 103. In-depth examination of a special topic in a small
group setting. Effective: 2018 Spring Quarter.</p><h2>STA 192—Internship in Statistics (1-12)</h2>
<p>Internship—3-36 hour(s); Term Paper...
我可以清楚地看到向量中有“ STA 190X”一词,但似乎无法提取它:
>str_detect(classes, "STA 190X")
[1] FALSE
>str_extract_all(classes, "STA 190X")
[[1]]
character(0)
但是如果我直接将一部分复制并粘贴到该函数中,它将起作用:
> str_detect("</p><h2>STA 190X—Seminar (1-2)</h2>", "STA 190X")
[1] TRUE
> str_extract_all("</p><h2>STA 190X—Seminar (1-2)</h2>", "STA 190X")
[[1]]
[1] "STA 190X"
任何人都知道这是为什么吗?
rvest
进行处理并提取正确的“节点”library(rvest)
library(stringr)
library(magrittr)
read_html("https://statistics.ucdavis.edu/courses/descriptions-undergrad") %>%
html_nodes("h2") %>%
html_text() %>%
str_c(collapse = ' ') %>%
str_extract(., "STA 190X")
#[1] "STA 190X"
str_detect(classes, "STA[^A-z0-9]190X")
[1] TRUE
说明:这是最奇怪的事情:
match_position <- gregexpr("STA[^\\s]*{1}190X", classes)[[1]][1] substr(classes, match_position - 10, gregexpr("STA[^A-z 0-9]{1}190X", classes)[[1]][1] + 17)
上面的代码返回匹配项,匹配项看起来像字符串'STA 190X',但不是。不可能是因为STA和190X之间不能有空格,因为
gregexpr
不会抓住它..."r.</p><h2>STA 190X—Seminar ("