---
title: "Ling 120, session 04: R basics 2 & frequency lists 2"
author:
   - name: "[Stefan Th. Gries](https://www.stgries.info)"
     affiliation:
        - UC Santa Barbara
        - JLU Giessen
     orcid: 0000-0002-6497-3958
date: "2027-01-26 12:34:56"
date-format: "DD MMM YYYY HH-mm-ss"
editor: source
format:
   html:
      page-layout: full
      code-fold: false
      code-link: true
      code-copy: true
      code-tools: true
      code-line-numbers: true
      code-overflow: wrap
      number-sections: true
      smooth-scroll: true
      toc: true
      toc-depth: 4
      number-depth: 4
      toc-location: left
      mainfont: Times New Roman
      monofont: Lucida Console
      tbl-cap-location: top
      fig-cap-location: bottom
      fig-width: 6
      fig-height: 6
      fig-format: png
      fig-dpi: 300
      fig-align: center
      embed-resources: true
      include-in-header:
         text: '<link rel="shortcut icon" href="https://www.stgries.info/favicon.ico" type="image/x-icon" />'
execute:
   cache: false
   echo: true
   eval: true
   warning: false
---

# Text processing 4: regular expressions 2

We first clear memory, load `magrittr`, and define `just.matches`:

```{r prepworkspace1}
rm(list=ls(all=TRUE)); library(magrittr)
just.matches <- function (search.expr, corpus.v, perl=TRUE, vectorize=TRUE, ...) {
   output <- regmatches(corpus.v, gregexpr(search.expr, corpus.v, perl=perl, ...))
   if (vectorize) { output <- unlist(output) }; return(output)
}
```

## Back-references

So far, whenever we used `gsub`, we specified a replacement string that would literally replace what was found, no matter what was found. That can be a problem because, oftentimes, we will need to make the replacement dependent on what was found. For instance, if we wanted to generate a concordance display by inserting tabs around a match, then a literal `replacement` argument messes with the original string:

```{r pastgsubs}
gsub("\\bthe\\b", "\tthe\t", "The Vorlons attacked the Shadows.", ignore.case=TRUE, perl=TRUE)
```

And that's of course becoming way more of a problem if our search involves something more regexy: How would we put tab stops around a verb and a particle/preposition in this example when we don't know what the replacement will be? After all, we don't know all the verbs and particles we might find.

```{r vpcs}
#| eval: false
"He=PNP slipped=V up=PART and=CONJ messed=V up=PART .=PUNCT"
```

We need a possibility to tell R

* to match something;
* to bear in mind what exactly it is that was matched;
* to replace the match by
   + what was matched (again) and
   + the added tab stops around it;

For that, we can use something called **back-references**: If something is parenthesized in the search pattern, R will memorize what it found and 'store it' in a slot identified by the number of the opening parentheses (i.e. as `\\1`, `\\2`, `\\3`, ...):

```{r backref1}
gsub("([^ ]+ed=V.*?[a-z]+=PART)",      # look for this
     "\t\\1\t",                        # replace by what you found betw tabs
     "He=PNP slipped=V up=PART and=CONJ messed=V up=PART .=PUNCT", # in here
     perl=TRUE)                        # using PCRE
```

Here, `\\1` refers to what was matched by `([^ ]+ed=V.*?[a-z]+=PART)`, because that unit's opening parenthesis was the 1st (and only) one.

This is actually a good point in time to introduce a feature called **free-spacing**, which allows you to break up regular expressions into smaller more easily understandable chunks, which can be explained with comments. For free-spacing, you need to

* begin your regex with `(?x)`;
* then break up your regex and add comments after some spaces and a `#`;
* but that means any space in your regex must be changed from ` ` to `\\s`.

This is what the last example would look like with free-spacing:

```{r backref1wfreespacg}
gsub("(?x)     # set free-spacing
     (         # make something the remembered unit \\1
     [^\\s]+   # not-a-space, 1+ times              = this is
     ed        # a 'past-tense' -ed                 = the verb
     =         # the separator between word & tag
     V         # the verb tag
     .*?       # stuff till the very next
     [a-z]+    # sequence of 1+ letters             = the particle
     =         # the separator between word & tag
     PART      # the particle tag
     )",       # the end of the remembered unit \\1
     "\t\\1\t",
     "He=PNP slipped=V up=PART and=CONJ messed=V up=PART .=PUNCT",
     perl=TRUE)
```

Here's another example, converting the bad month-day-year format into the good day-month-year format:

```{r backref2dates}
(American_dates <- c("5/15/1976", "2.15.1970", "1.9.2006"))
(British_dates <- gsub(
   "(\\d{1,2})\\D(\\d{1,2})\\D",
   "\\2/\\1/",
   American_dates,
   perl=TRUE))
```

This could look like this with free-spacing:

```{r backref2dateswfreespacg}
(British_dates <- gsub("(?x)    # set free-spacing
   (\\d{1,2})                   # 1 or 2 digits, memorize as \\1     = MM
   \\D                          # 1 non-digit (what separates MM and DD)
   (\\d{1,2})                   # 1 or 2 digits, memorize as \\2     = DD
   \\D",                        # 1 non-digit (what separates DD and YYYY)
   "\\2/\\1/", American_dates, perl=TRUE))
```

## Lookaround

Last regex construct: nearly all regexes we saw before consumed characters, but this one, **lookaround**, does not. It kind of involves using one part of a regex 'for reference' but doesn't consume it, so that another part *can* be matched and consumed. We distinguish 4 different kinds of lookaround depending on (i) in which direction you look and (ii) whether you reference the presence or the absence of something:

* lookahead: look to the right:
   - `(?=…)`: positive lookahead: match if some character(s) follow;
   - `(?!…)`: negative lookahead: match if some character(s) don't follow;
* lookbehind: look to the left:
   - `(?<=…)`: positive lookbehind: match if some character(s) precede;
   - `(?<!…)`: negative lookbehind: match if some character(s) don't precede.

Note: a lookbehind expression cannot involve variable lengths (i.e. basically regexes with quantifiers such as `*` or `+`).

We can actually explain this really well by revisiting last week. Remember, we wanted to create a case-insensitive frequency list of the British Component of the International Corpus of English ([ICE-GB] (https://www.ucl.ac.uk/english-usage/projects/ice-gb/)), which looks like this:

```{r icegbexample}
#| code-fold: false
noquote(current_corpus_file <- tolower(c(
   "DISMK,FRM {OK}",
   " NPHD,N(prop,sing) {Adam}",
   "DISMK,INTERJEC {uhm}",
   "PAUSE,PAUSE(short) {<,>}",
   " NPHD,PRON(inter) {what}",
   "INTOP,AUX(do,past) {did}",
   "  NPHD,PRON(pers) {you}",
   " MVB,V(cxtr,infin) {see}",
   "  P,PREP(ge) {as}",
   "  MVB,V(intr,ingp) {missing}")))
```

We needed to extract words from between the curly brackets and did this:

```{r icegbwordsold}
(current_words <- just.matches( # make current_words the result of
   "\\{.*?\\}",          # looking for stuff between (& incl.) curly brackets
   current_corpus_file)) # in current_corpus_file
(current_words <- gsub( # make current_words the result of replacing
   "[\\{\\}]", "",      # curly brackets by nothing
   current_words))      # in current_words
```

But now we can do that much more elegantly with positive lookbehind and positive lookahead:

```{r icegbwordsnew1}
just.matches(search.expr=
   "(?x)    # set free-spacing
   (?<=     # look to the left & see, but not consume,
   \\{      # an opening curly bracket
   )        # close positive lookbehind
   .*?      # then find the stuff till
   (?=      # you can look to the right & see, but not consume,
   \\}      # a closing curly bracket
   )",      # close positive lookahead, and done
   current_corpus_file)
```

We could in fact do this a bit better because the positive lookahead part is actually not necessary and makes this more complex than necessary:

```{r icegbwordsnew2}
just.matches(search.expr=
   "(?x)    # set free-spacing
   (?<=     # look to the left & see, but not consume,
   \\{      # an opening curly bracket
   )        # close positive lookbehind
   [^\\}]+", # then find non-closing curly bracket stuff, and done
   current_corpus_file)
```

Here's another example: Imagine you want to delete all annotation from this corpus line that is not a word or a part-of-speech tag, i.e. you want to delete "<whining>" and "<pause>" plus (!) whatever other such annotation your files might contain.

```{r whiningpauseexample}
(asd <- c("<w PNP>I <whining> <w VVB>like <w DEM>this <pause> <w NN1>book<p PUN>."))
```

In other words, you want to delete all things between angled brackets that do not begin with either "<w " or "<p " -- but how do you say that? Until now, The only way to say 'not' was `[^...]`, which involves single character alternatives, but you now need negative multi-character alternatives, so to speak. This is how it's done:

```{r whiningpausedeleting}
gsub("(?x)    # set free-spacing
     \\s*     # 0+ spaces, i.e. maybe 1+ spaces
     <        # the opening of the tag
     (?!      # after that, look to the right & do NOT see   <-----+
     [wp]     #    a w or a p, followed by                         |
     \\s      #    a space, followed by                            |
     [^>]+?   #    1+ non->s, till the very next                   |
     >        #    >                                               |
     )        #    end of neg look-ahead so, from after this <-----+
     [^>]+?   # 1+ non->s, till the very next
     >",      # >
     "",      # replace by nothing
     asd, perl=TRUE)
```

This kind of application is really important to make sure you can find sequences of word-tag pairs.

What about extracting the words from `asd`?

```{r whiningpauseextracting}
asd
just.matches(
   "(?x)      # set free-spacing
   (?<=       # look to the left and see <-----------+
   <             # an opening angular bracket        |
   w\\s          # a w, followed by a space          |
   ...           # followed by3 characters           |
   >             # the closing angular bracket       |
   )          # end of the positive lookahead <------+
   [^<]+",    # 1+ non->s
   asd) %>% trimws
```

# Revisiting frequency lists

We first clear memory and load `magrittr`:

```{r prepworkspace2}
rm(list=ls(all=TRUE)); library(magrittr)
just.matches <- function (search.expr, corpus.v, perl=TRUE, vectorize=TRUE, ...) {
   output <- regmatches(corpus.v, gregexpr(search.expr, corpus.v, perl=perl, ...))
   if (vectorize) { output <- unlist(output) }; return(output)
}
```

In this part of this session, we will revisit the issue of generating case-insensitive frequency lists of corpora. Last time, we did this for the ICE-GB using a regex approach that involved a sequence of `just.matches` followed by a `gsub`, and then we made this a bit more elegant above by switching to a lookaround approach. Now we will develop regexes that allow us to do the same for three other corpora that have no annotation or annotation that differs from that of the ICE-GB.

## Regex development: words in Brown untagged

In this part of the script, we will develop some regex(es) to prepare to generate a case-insensitive frequency list of the untagged version of the [Brown corpus](http://korpus.uib.no/icame/manuals/BROWN/INDEX.HTM). That corpus looks like this:

```{r brownuntexample}
#| code-fold: false
noquote(current_corpus_file <- tolower(c(
   "A01 0010    The Fulton County Grand Jury said Friday an investigation",
   "A01 0020 of Atlanta's recent primary election produced \"no evidence\" that",
   "A01 0030 any irregularities took place.   The jury further said in term-end",
   "A01 0040 presentments that the City Executive Committee, which had over-all",
   "A01 0050 charge of the election, \"deserves the praise and thanks of the")))
```

How could we process this? Use this [regexr page](https://regexr.com) or this [regex page](https://regex101.com) if you think it helps (it usually does ...).

```{r brownuntregexing}
# replace this with your answers/code
```

Ideally, you would now run the script from last week again, this time on the untagged version of the Brown corpus with the regex we just developed; if you do so (and you should, as you will see later), put the result in <_outputfiles/218_04_freqlists_brown_untagged.csv>.

## Regex development: words in Brown tagged

In this part of the script, we will develop some regex(es) to prepare to generate a case-insensitive frequency list of the tagged [Brown corpus](http://korpus.uib.no/icame/manuals/BROWN/INDEX.HTM). That corpus looks like this:

```{r browntexample}
#| code-fold: false
noquote(current_corpus_file <- tolower(c(
   "|SA01:1 the_AT Fulton_NP County_NN Grand_JJ Jury_NN said_VBD Friday_NR an_AT investigation_NN of_IN Atlanta's_NP$ recent_JJ primary_NN election_NN produced_VBD no_AT evidence_NN that_CS any_DTI irregularities_NNS took_VBD place_NN ._.",
   "|SA01:2 the_AT jury_NN further_RBR said_VBD in_IN term-end_NN presentments_NNS that_CS the_AT City_NN Executive_JJ Committee_NN ,_, which_WDT had_HVD over-all_JJ charge_NN of_IN the_AT election_NN ,_, deserves_VBZ the_AT praise_NN and_CC thanks_NNS of_IN the_AT City_NN of_IN Atlanta_NP for_IN the_AT manner_NN in_IN which_WDT the_AT election_NN was_BEDZ conducted_VBN ._.")))
```

How could we process this? Use this [regexr page](https://regexr.com) or this [regex page](https://regex101.com) if you think it helps (it usually does ...).

```{r browntregexing}
# replace this with your answers/code
```

Ideally, you would now run the script from last week again, this time on the tagged version of the Brown corpus with the regex we just developed; if you do so (and you should, as you will see later), put the result in <_outputfiles/218_04_freqlists_brown_tagged.csv>.

## Regex development: words in the BNC XML

In this part of the script, we will develop some regex(es) to prepare to generate a case-insensitive frequency list of a sample of the XML version of the [British National Corpus](http://www.natcorp.ox.ac.uk). That corpus looks like this:

```{r bncxmlexample}
#| code-fold: false
noquote(current_corpus_file <- tolower(c(
   '<s n="1"><w type="PNP" lemma="they">They </w><w type="VVD" lemma="begin">began </w><w type="VVG" lemma="open">opening </w><w type="AT0" lemma="every">every </w><w type="NN1" lemma="door">door </w><w type="CJS" lemma="as">as </w><w type="PNP" lemma="they">they </w><w type="VVD" lemma="walk">walked </w><w type="AVP" lemma="up">up </w><w type="DPS" lemma="it">its </w><w type="NN1" lemma="length">length</w><c type="PUN">.</c></s>',
   '<s n="2"><w type="NP0" lemma="dorothy">Dorothy</w><c type="PUN">, </c><w type="PRP" lemma="in">in </w><w type="DPS" lemma="she">her </w><w type="NN1" lemma="time">time</w><c type="PUN">, </c><w type="VHD" lemma="have">had </w><w type="VBN" lemma="be">been </w><w type="AT0" lemma="an">an </w><w type="AJ0" lemma="active">active </w><w type="NN1" lemma="member">member </w><w type="PRF" lemma="of">of </w><w type="AT0" lemma="an">an </w><w type="NN1" lemma="organisation">organisation </w><w type="VVN-VVD" lemma="call">called </w><w type="AT0" lemma="the">the </w><w type="NN1" lemma="noise">Noise </w><w type="NN1" lemma="reduction">Reduction </w><w type="NN1" lemma="society">Society</w><c type="PUN">, </c><w type="DTQ" lemma="which">which </w><w type="VHD" lemma="have">had </w><w type="VVN" lemma="campaign">campaigned </w><w type="AV0" lemma="valiantly">valiantly </w><w type="CJC" lemma="and">and </w><w type="AV0" lemma="indiscriminately">indiscriminately </w><w type="PRP" lemma="against">against </w><w type="NN2" lemma="lawnmower">lawnmowers </w><w type="CJC" lemma="and">and </w><w type="NN1" lemma="jet">jet </w><w type="NN0" lemma="aircraft">aircraft</w><c type="PUN">.</c></s>')))
```

How could we process this? Use this [regexr page](https://regexr.com) or this [regex page](https://regex101.com) if you think it helps (it usually does ...).

```{r bncxmlregexingwords}
# replace this with your answers/code
```

Ideally, you would now run the script from last week again, this time on the tagged version of the Brown corpus with the regex we just developed; if you do so (and you should, as you will see later), put the result in <_outputfiles/218_04_freqlists_bncxml_sample.csv>.

## Regex development: lemmas in the BNC XML

Additional little exercise: how could you extract all *lemmas* from that same corpus snippet? Use this [regexr page](https://regexr.com) or this [regex page](https://regex101.com) if you think it helps (it usually does ...).

```{r bncxmlregexinglemmas}
# replace this with your answers/code
```

# Session info

```{r sessionInfo}
sessionInfo()
```
