Concordances¶
A search returns positions in a corpus, and everything after it is a decision about how to lay those positions out. This notebook works through the concordance side of polars_corpus:
- Searching --
plc.search, and theSearchResultsit hands back. - Concordance lines --
concordance, the list columns it returns, and the viewer. - Positions --
plc.kwic, which reads L1, R1 or the node out of a line, so thatgroup_by,sortandfiltercan work on one slot at a time. - Getting the lines out -- joining those lists into strings, for a CSV file or a formatted table.
- Hits against corpus size -- writing the matches back onto the corpus, so that hits and tokens can be counted in one pass.
The library supplies the matcher, the concordance layout and kwic; the counting, filtering and sorting in between are ordinary Polars.
import polars as pl
import polars.selectors as cs
import polars_corpus as plc
import great_tables as gt
pl.Config.set_tbl_rows(12)
pl.Config.set_fmt_table_cell_list_len(5)
pl.Config.set_thousands_separator(",")
polars.config.Config
The corpus¶
These examples use AMALGUM, the automatically annotated corpus of English that the word frequencies notebook describes: 3.85 million tokens of seven genres, one row per token in corpus order, annotated with pos and lemma and carrying a file_id and a text_type for the document each token came from.
file_id does more work here than it does in a frequency count. plc.search takes file_id_column="file_id" by default, and both the matcher and the context respect it: no match spans two files, and the words to the left and right of a match stop at the edge of the file the match sits in rather than running on into the next text.
c = pl.read_parquet("../../data/amalgum.parquet")
c
| token | pos | lemma | sentence_tag | file_id | text_type |
|---|---|---|---|---|---|
| str | str | str | str | str | str |
| "1." | "LS" | "1." | "B" | "AMALGUM_academic_acrylamide" | "academic" |
| "Introduction" | "NN" | "introduction" | "I" | "AMALGUM_academic_acrylamide" | "academic" |
| "Acrylamide" | "NNP" | "Acrylamide" | "B" | "AMALGUM_academic_acrylamide" | "academic" |
| "," | "," | "," | "I" | "AMALGUM_academic_acrylamide" | "academic" |
| "a" | "DT" | "a" | "I" | "AMALGUM_academic_acrylamide" | "academic" |
| "thermal" | "JJ" | "thermal" | "I" | "AMALGUM_academic_acrylamide" | "academic" |
| … | … | … | … | … | … |
| "'re" | "VBP" | "be" | "I" | "AMALGUM_whow_yacht" | "whow" |
| "out" | "IN" | "out" | "I" | "AMALGUM_whow_yacht" | "whow" |
| "of" | "IN" | "of" | "I" | "AMALGUM_whow_yacht" | "whow" |
| "the" | "DT" | "the" | "I" | "AMALGUM_whow_yacht" | "whow" |
| "harbor" | "NN" | "harbor" | "I" | "AMALGUM_whow_yacht" | "whow" |
| "." | "." | "." | "I" | "AMALGUM_whow_yacht" | "whow" |
Searching¶
plc.search runs a query in the simple query language and returns a SearchResults, which holds the corpus and one span per match -- where the matches are, not what they say. The words themselves stay in the corpus and are read back out only when a method needs them, so the results themselves cost no more than their spans. The repr gives the query and the count. Word-form queries are case-insensitive, so the 809 hits include Light and LIGHT.
m = plc.search(c, "light")
m
SearchResults<'light'; 809 matches>
view builds the same lines concordance builds and draws them in a widget that pages through them page_size=25 at a time and sorts and filters them in place. It returns nothing -- it draws -- so it is where a query gets looked at rather than where an analysis starts. Everything below takes the frame instead.
m.view(window=5)
concordance lays the matches out one row per match: token for the matched words, token_left_context and token_right_context for the window=5 words on either side. All three hold a list of tokens rather than a joined string, and that is what makes a line something to compute with -- list.contains filters on the words of the context the way a mask filters on any other column. metadata="file_id" adds one scalar per line, read off the match's first token.
The filter finds two lines, and they are the same line twice. AMALGUM_fiction_brooding and AMALGUM_fiction_gloom are both the opening of Heart of Darkness: duplicated texts are an ordinary hazard of a large corpus, and here it is the metadata column that makes the duplication visible at all.
m.concordance(window=5, metadata="file_id").filter(
pl.col("token_left_context").list.contains("benign")
)
| token_left_context | token | token_right_context | file_id |
|---|---|---|---|
| list[str] | list[str] | list[str] | str |
| ["a", "benign", "immensity", "of", "unstained"] | ["light"] | [";", "the", "very", "mist", "on"] | "AMALGUM_fiction_brooding" |
| ["a", "benign", "immensity", "of", "unstained"] | ["light"] | [";", "the", "very", "mist", "on"] | "AMALGUM_fiction_gloom" |
Counting the matches¶
m is rebound here, and everything below is about shall rather than light.
A bare + in the simple query language stands for exactly one intervening token, so + shall + matches three tokens: something, shall, something. Widening the query like this is one way of asking what fills the slots around a word -- the neighbours become part of the match. The 275 matches are the shalls that have a token on each side of them within the same file.
m = plc.search(c, "+ shall +")
m
SearchResults<'+ shall +'; 275 matches>
concordance takes an expression as readily as a column name, so the case fold happens on the way out and the corpus keeps its capitals. The column is still named token, after the root of the expression.
window defaults to 0, which leaves the context columns off entirely: here the three matched tokens are the whole line.
conc = m.concordance(pl.col("token").str.to_lowercase())
conc
| token |
|---|
| list[str] |
| ["we", "shall", "use"] |
| ["reference", "shall", "be"] |
| ["adder", "shall", "be"] |
| ["reference", "shall", "be"] |
| ["we", "shall", "consider"] |
| ["we", "shall", "note"] |
| … |
| ["i", "shall", "not"] |
| ["one", "shall", "lay"] |
| ["i", "shall", "not"] |
| ["they", "shall", "never"] |
| ["we", "shall", "."] |
| ["we", "shall", "keep"] |
Polars groups a list column by value, so this counts whole trigrams -- 199 distinct ones over the 275 matches, i shall be the most frequent at 18. Folding the case in the concordance expression is what puts sentence-initial We shall be in the same group as we shall be.
conc.group_by(pl.col("token")).len().sort(by="len", descending=True)
| token | len |
|---|---|
| list[str] | u32 |
| ["i", "shall", "be"] | 18 |
| ["i", "shall", "not"] | 11 |
| ["we", "shall", "be"] | 8 |
| ["i", "shall", "have"] | 6 |
| ["what", "shall", "we"] | 4 |
| ["“", "shall", "i"] | 4 |
| … | … |
| ["we", "shall", "speed"] | 1 |
| ["who", "shall", "command"] | 1 |
| ["we", "shall", "note"] | 1 |
| ["you", "shall", "go"] | 1 |
| ["reaped", "shall", "rejoice"] | 1 |
| ["i", "shall", "turn"] | 1 |
Reading one position with kwic¶
plc.kwic names a position on a concordance line and returns an expression for the word standing there: "L1" for the word immediately left of the match, "R2" for the second one to its right, "node" for the match itself joined into a string. Signed integers say the same thing the CQP way, -1 for L1 and 0 for the node. Because it is an expression and nothing more, it goes wherever a column would -- group_by, sort, filter, select -- and takes an alias like any other.
The positions it names are context positions, which is not where the trigram query put the neighbours. In + shall + they are inside the match, so they are node-internal, and kwic("node") would return all three words joined together. Asking about them as context instead means matching shall alone and letting the window supply them. Both queries find 275 lines, since every shall in AMALGUM has a token on either side of it within its file.
shall = plc.search(c, "shall")
conc = shall.concordance(pl.col("token").str.to_lowercase(), window=5)
conc
| token_left_context | token | token_right_context |
|---|---|---|
| list[str] | list[str] | list[str] |
| ["the", "carry", "overflow", ".", "we"] | ["shall"] | ["use", "some", "legends", "for", "the"] |
| ["the", "approximate", "adder", "of", "reference"] | ["shall"] | ["be", "referred", "to", "as", "loawa"] |
| ["1", "d.", "this", "approximate", "adder"] | ["shall"] | ["be", "referred", "to", "as", "approx5"] |
| ["approximate", "adder", "presented", "in", "reference"] | ["shall"] | ["be", "called", "heaa", ",", "which"] |
| ["various", "possible", "transitions", ",", "we"] | ["shall"] | ["consider", "three", "cases", "in", "detail"] |
| ["in", ".", "undoubtedly", ",", "we"] | ["shall"] | ["note", "the", "fundamental", "results", "of"] |
| … | … | … |
| ["regard", "to", "him", ",", "i"] | ["shall"] | ["not", "trouble", "myself", "to", "describe"] |
| ["no", ",", "but", "no", "one"] | ["shall"] | ["lay", "hands", "on", "my", "master"] |
| ["his", "pardon", ".", """, "i"] | ["shall"] | ["not", ",", """, "said", "the"] |
| ["bear", "it", ".", "but", "they"] | ["shall"] | ["never", "laugh", "at", "my", "children"] |
| [",", "'", "and", "talk", "we"] | ["shall"] | [".", """, "earlier", "on", "thursday"] |
| ["shelling", "residential", "areas", ".", "we"] | ["shall"] | ["keep", "on", "targeting", "them", ","] |
The same question is now a group_by on an expression, since kwic("L1") reads the last element of token_left_context. The alias is worth the keystrokes: without it the count table comes back with a column called token_left_context holding a single word.
The slot is overwhelmingly pronominal -- i 89, we 47, you 12, he 10, with what and a comma next at seven each, and then a tail of nouns occurring once apiece.
conc.group_by(plc.kwic("L1").alias("L1")).len().sort(by="len", descending=True)
| L1 | len |
|---|---|
| str | u32 |
| "i" | 89 |
| "we" | 47 |
| "you" | 12 |
| "he" | 10 |
| "what" | 7 |
| "," | 7 |
| … | … |
| "husband" | 1 |
| "stations" | 1 |
| "as" | 1 |
| "ceremony" | 1 |
| "record" | 1 |
| "fool" | 1 |
The other side of the node is the same call with the position changed. be alone takes 52 of the 275 lines and not 24, while the 16 lines of shall i are the inverted order of a question rather than anything filling a complement slot.
conc.group_by(plc.kwic("R1").alias("R1")).len().sort(by="len", descending=True)
| R1 | len |
|---|---|
| str | u32 |
| "be" | 52 |
| "not" | 24 |
| "have" | 16 |
| "i" | 16 |
| "never" | 7 |
| "we" | 6 |
| … | … |
| "assume" | 1 |
| "you" | 1 |
| "ascend" | 1 |
| "expect" | 1 |
| "fold" | 1 |
| "continue" | 1 |
kwic reads its position out of whichever concordance it is handed, and the column argument says which one. A concordance of pos has pos_left_context and pos_right_context, so plc.kwic("L1", "pos") is the tag of the word before the match. These are the same 275 lines as above, described by tag instead of by form.
tags = shall.concordance("pos", window=5)
tags.group_by(plc.kwic("L1", "pos").alias("L1")).len().sort(by="len", descending=True)
| L1 | len |
|---|---|
| str | u32 |
| "PRP" | 172 |
| "NN" | 34 |
| "WP" | 12 |
| "NNS" | 12 |
| "," | 7 |
| "``" | 6 |
| … | … |
| "EX" | 1 |
| "UH" | 1 |
| "-RRB-" | 1 |
| "VBD" | 1 |
| ":" | 1 |
| "DT" | 1 |
Tagging collapses the tails the word tables had into twenty categories on the left and ten on the right. 172 of the 275 left neighbours are PRP, and 34 more NN; on the right, 187 are the bare infinitive VB a modal takes, 48 are adverbs coming between the modal and its verb, and 26 are the inverted PRP subjects.
tags.group_by(plc.kwic("R1", "pos").alias("R1")).len().sort(by="len", descending=True)
| R1 | len |
|---|---|
| str | u32 |
| "VB" | 187 |
| "RB" | 48 |
| "PRP" | 26 |
| "," | 5 |
| "." | 3 |
| "PRP$" | 2 |
| "NNP" | 1 |
| ":" | 1 |
| "IN" | 1 |
| "VBG" | 1 |
Sorting¶
Sorting a concordance means sorting on its positions, so it is sort with kwic expressions in it. sort(kwic("L1"), kwic("L2")) is the classic left sort: lines sharing a left neighbour come out in one block, and the word before that orders them within it.
Punctuation sorts ahead of letters, so the table opens with a stray apostrophe and then the seven lines with a comma at L1, ordered among themselves by what stands at L2 -- now, qualification, rome, then, then, unborn, you -- followed by the three with a full stop and one with a semicolon. Further down the same thing happens at the scale of the 89 i lines and the 47 we lines the L1 table counted.
A position the context does not reach comes out null, whether because the window is too short or because the context stopped at a file boundary. Null sorts first, so nulls_last=True keeps those lines from heading the table.
conc.sort(plc.kwic("L1"), plc.kwic("L2"), nulls_last=True).head(12)
| token_left_context | token | token_right_context |
|---|---|---|
| list[str] | list[str] | list[str] |
| ["gray", "veil", ".", """, "'"] | ["shall"] | ["be", "together", ",", "breathe", "and"] |
| ["might", "be", ".", "now", ","] | ["shall"] | ["i", "take", "you", "in", "hand"] |
| [",", "for", "further", "qualification", ","] | ["shall"] | ["be", "capable", "of", "sitting", "boxed"] |
| ["and", "authority", "of", "rome", ","] | ["shall"] | ["ebbe", "and", "decay", "still", "more"] |
| [""", "how", ",", "then", ","] | ["shall"] | ["i", "fear", "that", "thin", "air"] |
| ["mock", "mail-coach", ".", "then", ","] | ["shall"] | ["wondering", "crowds", "observe", "how", "that"] |
| ["amburgh", ",", "yet", "unborn", ","] | ["shall"] | ["break", "wild", "horses", "by", "his"] |
| [",", "i", "promise", "you", ","] | ["shall"] | ["be", "written", "of", "a", "morning"] |
| ["a", "most", "precious", "possession", "."] | ["shall"] | ["i", "go", "get", "it", "?"] |
| ["now", "about", "the", "presents", "."] | ["shall"] | ["we", "wait", "until", "tomorrow", ","] |
| ["one", "of", "the", "words", "."] | ["shall"] | ["i", "compare", "you", "to", "a"] |
| [";", "made", ";", "suffer", ";"] | ["shall"] | [";", "should", ";", "will", ";"] |
Getting the lines out¶
The list columns are what makes a line computable, and they are also what write_csv refuses: given one it raises ComputeError: CSV format does not support nested data. as_str=True joins every List(String) column -- the match, both contexts, and any $var: binding column -- into one space-separated string, and leaves everything else as it is, so metadata scalars stay scalars and a list of structs from an expression like pl.struct("token", "pos") stays a list of structs.
That is the whole of an export. The frame below writes straight out, one row per line, with the context in two columns and the file it came from in a third.
export = shall.concordance("token", window=5, metadata="file_id", as_str=True)
export.write_csv("/tmp/shall.csv")
export.head()
| token_left_context | token | token_right_context | file_id |
|---|---|---|---|
| str | str | str | str |
| "the carry overflow . We" | "shall" | "use some legends for the" | "AMALGUM_academic_adder" |
| "The approximate adder of Refer… | "shall" | "be referred to as LOAWA" | "AMALGUM_academic_adder" |
| "1 d. This approximate adder" | "shall" | "be referred to as APPROX5" | "AMALGUM_academic_adder" |
| "approximate adder presented in… | "shall" | "be called HEAA , which" | "AMALGUM_academic_adder" |
| "various possible transitions ,… | "shall" | "consider three cases in detail" | "AMALGUM_academic_dynamical" |
Sorting needs the lists and writing a file needs the strings, so the two cannot be had from one call -- as_str=True joins before there is a position left to sort on. The order is sort first, join last, and the join is one selector: cs.by_dtype(pl.List(pl.String)) picks exactly the columns as_str would have joined.
conc.sort(plc.kwic("L1"), plc.kwic("L2"), nulls_last=True).with_columns(
cs.by_dtype(pl.List(pl.String)).list.join(" ")
).head(12)
| token_left_context | token | token_right_context |
|---|---|---|
| str | str | str |
| "gray veil . " '" | "shall" | "be together , breathe and" |
| "might be . now ," | "shall" | "i take you in hand" |
| ", for further qualification ," | "shall" | "be capable of sitting boxed" |
| "and authority of rome ," | "shall" | "ebbe and decay still more" |
| "" how , then ," | "shall" | "i fear that thin air" |
| "mock mail-coach . then ," | "shall" | "wondering crowds observe how t… |
| "amburgh , yet unborn ," | "shall" | "break wild horses by his" |
| ", i promise you ," | "shall" | "be written of a morning" |
| "a most precious possession ." | "shall" | "i go get it ?" |
| "now about the presents ." | "shall" | "we wait until tomorrow ," |
| "one of the words ." | "shall" | "i compare you to a" |
| "; made ; suffer ;" | "shall" | "; should ; will ;" |
A formatted table¶
Joined strings are what a table renderer wants too. .style hands a Polars frame to great_tables, and a KWIC display is then a question of alignment: right-align the left context, centre the match, left-align the right context, and the node falls into a column down the middle. sample(10, seed=0) cuts the 275 lines down to a readable ten and fixes which ten, and cols_label clears the three headings, which name columns nobody reading the table needs named.
tbl = (
shall.sample(10, seed=0)
.concordance("token", window=8, as_str=True)
.style.tab_header(title=gt.md("*shall* in AMALGUM"))
.cols_align(align="right", columns="token_left_context")
.cols_align(align="center", columns="token")
.cols_align(align="left", columns="token_right_context")
.cols_label(token_left_context="", token="", token_right_context="")
.tab_options(table_font_names=gt.system_fonts("industrial"))
)
tbl
| shall in AMALGUM | ||
| -- I beg of you , if God | shall | have given you any skill in letters , |
| them are concerned , so that all trades | shall | be equally attractive to persons having natural tastes |
| only daughter ; -- and the wedding ceremony | shall | now be performed . " As the king |
| send me away , I think that I | shall | kill myself . Wingrave ! ” |
| After submission of the form , entrance exams | shall | be conducted upon the scheduled date . This |
| vigorous , ongoing and continuous negotiations , and | shall | make every effort to conclude an agreement before |
| out and kill many Englishmen . Your name | shall | be hated and cursed the length and breadth |
| through in a very few minutes . “ | Shall | I turn back ? ” meditated he . |
| do n’t see any contradictions . Since we | shall | always remain a small land and a small |
| those days to come , when mail-coach guards | shall | no longer be judges of horse-flesh — when |
Hits against corpus size¶
metadata='text_type' puts the genre on every line, so a group_by over the concordance counts hits per genre. Two things are wrong with the answer. The counts are raw, and the genres are not the same size; and voyage is missing from the table altogether, because a genre with no hits contributes no lines to count.
shall.concordance("token", metadata="text_type").group_by("text_type").len()
| text_type | len |
|---|---|
| str | u32 |
| "whow" | 4 |
| "interview" | 18 |
| "bio" | 6 |
| "news" | 15 |
| "academic" | 11 |
| "fiction" | 221 |
with_spans_as_chunks runs the other way from concordance: rather than pulling the matches out of the corpus it writes them back onto it, as a column of BIO tags with "B" on the first token of each match, "I" on the rest of it, and "O" on every token no match covers. What comes back is the corpus with one column added, so the hits and the tokens can be counted in the same aggregation -- (pl.col("spans") == "B").sum() counts matches, since only the first token of each carries a B, and pl.len() counts tokens. Numerator and denominator arrive together and the rate follows.
Every genre is there now, voyage with none of the 275. AMALGUM's genres are close enough in size, 498,310 tokens to 660,773, that normalizing barely disturbs the ranking; what it changes is what can be said. shall runs at 422.6 per million words in fiction against 35.9 in interviews and 19.6 in academic writing, and those are numbers to set beside another corpus, where a count of 221 is not.
(
shall.with_spans_as_chunks()
.group_by("text_type")
.agg(
(pl.col("spans") == "B").sum().alias("hits"),
pl.len().alias("tokens"),
)
.with_columns(per_million=(pl.col("hits") / pl.col("tokens") * 1e6).round(1))
.sort(by="per_million", descending=True)
)
| text_type | hits | tokens | per_million |
|---|---|---|---|
| str | u32 | u32 | f64 |
| "fiction" | 221 | 522,936 | 422.6 |
| "interview" | 18 | 500,971 | 35.9 |
| "news" | 15 | 590,830 | 25.4 |
| "academic" | 11 | 562,642 | 19.6 |
| "bio" | 6 | 498,310 | 12.0 |
| "whow" | 4 | 513,967 | 7.8 |
| "voyage" | 0 | 660,773 | 0.0 |