## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(
  message = FALSE,
  warning = FALSE,
  comment = "#>"
)
source("cache-hook.R")

## ----libs, message=FALSE, warning=FALSE---------------------------------------
library(textpress)
library(dplyr)
library(DT)

## ----web-urls, cache_rds = c("feeds", "web_urls")-----------------------------
# feeds <- c(
#   textpress::rss_politics |>
#     filter(source == "Pew Research Center") |>
#     pull(url),
#   "https://theconversation.com/us/politics/articles.atom"
# )
# 
# web_urls <- textpress::fetch_rss(feeds) |>
#   select(-doc_id) |>
#   distinct(url, .keep_all = TRUE)

## ----web-text, cache_rds = c("web_text_list", "web_text")---------------------
# web_text_list <- web_urls |>
#   textpress::read_urls(cores = 4)
# 
# web_text <- web_text_list$text |>
#   mutate(doc_id = match(url, unique(url))) |>
#   relocate(doc_id, .before = 1)

## ----web-ss-------------------------------------------------------------------
web_ss <- web_text |>
  textpress::nlp_split_sentences(by = c('doc_id', 'node_id'))

## ----patterns-----------------------------------------------------------------
patterns <- list(
  margin = "\\b\\d{1,2}(?:\\.\\d)?[- ](?:percentage[- ])?points?\\b",
age_range = paste(
  "\\b(?:aged?(?:\\s+between)?|ages?)\\s+\\d{2,3}(?:(?:\\s*(?:[-–]|to|and)\\s*\\d{2,3})|(?:\\s+and\\s+(?:older|younger|over|under)))\\b",
  "\\bunder\\s+\\d{2}(?!\\d|,|%)\\b",
  "\\b\\d{2,3}(?!\\d|,|%)\\s*(?:\\+|and\\s+(?:older|younger|over|under))\\b",
  sep = "|"
),
  from_to   = "\\bfrom\\s+\\d+\\s+to\\s+\\d+\\b"
)

## ----out-age-range------------------------------------------------------------
fs <- web_ss |>
  textpress::search_regex(
    query = patterns$age_range,
    by = c('doc_id', 'node_id'),
    highlight = c('<span style="background:#a6cbe1;">', '</span>')
    )

if (!is.null(fs) && nrow(fs) > 0) {
  fs |>
    distinct(text, .keep_all = TRUE) |>
    select(doc_id, node_id, pattern, text) |>
    DT::datatable(rownames = FALSE, escape = FALSE)
}

## ----out-from-to--------------------------------------------------------------
fs1 <- web_ss |>
  textpress::search_regex(
    query = patterns$from_to,
    by = c('doc_id', 'node_id'),
    highlight = c('<span style="background:#fdc4a8;">', '</span>')
    )

if (!is.null(fs1) && nrow(fs1) > 0) {
  fs1 |>
    distinct(text, .keep_all = TRUE) |>
    select(doc_id, node_id, pattern, text) |>
    DT::datatable(rownames = FALSE, escape = FALSE)
}

## ----out-margin---------------------------------------------------------------
fs2 <- web_ss |>
  textpress::search_regex(
    query = patterns$margin,
    by = c('doc_id', 'node_id'),
    highlight = c('<span style="background:#c8e6c9;">', '</span>')
    )

if (!is.null(fs2) && nrow(fs2) > 0) {
  fs2 |>
    distinct(text, .keep_all = TRUE) |>
    select(doc_id, node_id, pattern, text) |>
    DT::datatable(rownames = FALSE, escape = FALSE)
}

