Created
June 2, 2017 15:14
-
-
Save expersso/e240bf2e7bee870c28148ae4c681dcff to your computer and use it in GitHub Desktop.
Pig latin translator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(stringr) | |
library(purrr) | |
vowels <- c("a", "e", "i", "o", "u") | |
is_vowel <- function(l) l %in% c(vowels, toupper(vowels)) | |
is_capitalized <- . %>% substr(1, 1) %>% str_detect("[[:upper:]]") | |
split_at <- function(x, i) split(x, cumsum(seq_along(x) %in% i)) | |
pigify_word <- function(word) { | |
ltrs <- strsplit(word, "")[[1]] | |
first_vowel <- detect_index(ltrs, is_vowel) | |
split_at(ltrs, first_vowel) %>% | |
rev() %>% | |
flatten_chr() %>% | |
c("a", "y") %>% | |
paste(collapse = "") | |
} | |
word_apply <- function(text, f, ...) { | |
words <- str_split(text, "\\b")[[1]] | |
capitalized_words <- map_lgl(words, is_capitalized) %>% which() | |
words %>% | |
map_if(~str_detect(., "\\w"), f, ...) %>% | |
map_at(capitalized_words, stringi::stri_trans_totitle) %>% | |
paste(collapse = "") | |
} | |
url("http://history.eserver.org/gettysburg-address.txt") %>% | |
readLines() %>% | |
.[4:26] %>% | |
paste(collapse = "") %>% | |
word_apply(pigify_word) %>% | |
strwrap(60) %>% | |
cat(sep = "\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment