/
sentences_intro.html
509 lines (390 loc) · 14.8 KB
/
sentences_intro.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
<!DOCTYPE html>
<html lang="" xml:lang="">
<head>
<title>Cooking with GermaParl</title>
<meta charset="utf-8" />
<meta name="date" content="2023-12-14" />
<script src="sentences_intro_files/header-attrs-2.25/header-attrs.js"></script>
<link rel="stylesheet" href="css/default.css" type="text/css" />
<link rel="stylesheet" href="css/metropolis.css" type="text/css" />
<link rel="stylesheet" href="css/robot-fonts.css" type="text/css" />
<link rel="stylesheet" href="css/polminify.css" type="text/css" />
</head>
<body>
<textarea id="source">
class: center, middle, inverse, title-slide
.title[
# Cooking with GermaParl
]
.date[
### 2023-12-14
]
---
# Purpose and Motivation
* GermaParl2 comprises **rich structural annotation** on the level of protocols (such as the date or the legislative period) and the level of speakers (such as a speakers name or parliamentary group)
* as seen in previous cookbooks, these can be used to **create meaningful subcorpora** for substantive analysis
* but even beyond that, the corpus contains **annotation below the level of speeches** in forms of paragraph and sentence annotation
* sentences can provide natural **units of analysis** with semantic meaning (for a comprehensive discussion see Däubler et al. 2012)
* sentence annotations can be used for a variety of **use cases**
---
# Encoding of Sentences
* sentences are annotated using **Stanford CoreNLP** (https://stanfordnlp.github.io/CoreNLP/)
* sentences are encoded as the **structural attribute** `s` in GermaParl2
* in contrast to other annotations in GermaParl, the sentence annotation **does not have values**; they describe regions in terms of start and end positions of sentences
* `polmineR` indicates the missing values when called with `s_attributes()`:
```r
s_attributes("GERMAPARL2", "s")
```
```
## ! s-attribute `s` does not have values, returning NA
```
```
## [1] NA
```
---
# Sentences and the tree structure
```r
corpus("GERMAPARL2") %>% polmineR::tree_structure()
```
```
## protocol [lp│no│date│year│url│filetype]
## |
## └─ speaker [who│name│party│parlgroup│role]
## |
## └─ p [type]
## |
## └─ s
## |
## └─ ne [type]
```
---
# Splitting Objects into Sentences
`polmineR` makes it easy to split a (sub)corpus into sentences
```r
sentences <- corpus("GERMAPARL2") |>
subset(protocol_date == "1949-12-14") |>
split(s_attribute = "s", values = FALSE)
```
* the `values` argument of `split()` makes missing **values** explicit, but this is not strictly necessary
* the output is a bundle of subcorpora, each containing a single sentence
* splitting by sentences can also be done for corpora with sentence annotation (caution: GermaParl2 is quite large)
---
# Splitting Objects into Sentences
* subcorpus bundles can be used as usual
* one example would be to decode the sentences as strings in their word order for further analysis
* this could be useful for word embeddings or classification tasks which rely on word order
```r
sentences_ts <- get_token_stream(sentences)
```
* the sentence annotation is not always perfect though:
```r
sentences_ts[[693]]
```
```
## [1] "—" "Ich" "schließe" "die" "23" "."
```
```r
sentences_ts[[694]]
```
```
## [1] "Sitzung" "des" "Deutschen" "Bundestags" "."
```
---
# Sentence-Term-Matrices
* the sentence bundle can also be used as input to create a **Document-Term-Matrix** (in this case a sentence-term-matrix)
* potentially useful for **machine learning approaches** which rely on a **Bag-of-Words** representation of sentences
* examples: Sentence Similarity, Weighting of Terms
```r
dtm <- polmineR::as.DocumentTermMatrix(sentences, p_attribute = "word")
```
---
# Sentence-Term-Matrices
```r
tm::inspect(dtm)
```
```
## <<DocumentTermMatrix (documents: 695, terms: 3255)>>
## Non-/sparse entries: 13796/2248429
## Sparsity : 99%
## Maximal term length: 32
## Weighting : term frequency (tf)
## Sample :
## Terms
## Docs , . daß den der des die in und zu
## 36563 38 1 0 0 0 0 2 0 0 0
## 36589 8 1 1 1 4 0 2 3 2 1
## 36619 9 1 2 3 12 0 2 2 2 2
## 36643 7 1 0 0 1 1 2 1 0 1
## 36674 8 1 3 1 3 0 4 3 4 1
## 36695 10 1 4 0 3 1 4 1 3 0
## 36717 5 1 3 0 2 1 0 2 1 1
## 36733 5 1 0 1 2 2 2 2 3 0
## 36777 5 1 1 0 4 2 7 1 4 0
## 36787 6 1 1 1 4 0 0 3 2 1
```
---
# Using Sentences as Context Windows
* the boundaries of sentences can be used to define **context windows** of query terms
* this can be useful to limit the analysis to relevant context words or to identify meaningful multi-word query terms
* `polmineR` provides two ways to make use of the sentence annotation in these scenarios:
#### 1) Sentence Annotation as a `boundary`:
* the maximum number of tokens in the context window is determined by the values of `left` and `right` but the context does not extend over the boundary of a sentence
```r
corpus("GERMAPARL2") |>
kwic(query = "Demokratie",
boundary = "s",
left = 20,
right = 20)
```
---
# Using Sentences as Context Windows
#### 2) Sentence Annotation as Context
* the context window is determined by the **structural attribute** - here `s` - defined by `region` and a number of sentences in `left` and `right`
```r
corpus("GERMAPARL2") |>
kwic(query = "Demokratie",
region = "s",
left = 0,
right = 0)
```
* the annotation of `left` and `right` determines **additional context** in terms of sentences `s`
* i.e. if `s` = 0, then the context window comprises of the same sentence as the query term
---
# Using Sentences as Context Windows
* changing the values of `left` and `right` to 1 adds one additional sentence as context
```r
corpus("GERMAPARL2") |>
kwic(query = "Demokratie",
region = "s",
left = 1,
right = 1)
```
* this is equivalent to the following syntax:
```r
corpus("GERMAPARL2") |>
kwic(query = "Demokratie",
left = c("s" = 1),
right = c("s" = 1))
```
---
# Using Sentences as Context Windows
* this also applies to values passed to other parameters such as `positivelist` and `stoplist`:
```r
corpus("GERMAPARL2") |>
kwic(query = "Demokratie",
region = "s",
left = 0,
right = 0,
positivelist = "Krise"
)
```
```
## ... filtering by positivelist
```
```
## ... number of hits dropped due to positivelist: 37002
```
```
## ... update count statistics for slot cpos
```
**Note:** Sentences which contain a query term more than once show up in the output of `kwic` more than once
---
# Using Sentences in CQP Queries
* as noted in the CQP manual, "most linguistic queries should include the restriction within s to avoid crossing sentence boundaries" (https://cwb.sourceforge.io/files/CQP_Manual/4_2.html)
* this can be achieved with the syntax used in the following query (results on the next slide)
```r
sc <- corpus("GERMAPARL2") |> subset(protocol_lp == 15)
count(sc,
query = '"Bundesministerium.*" []{1,5} [xpos = "NN"] within s',
cqp = TRUE,
breakdown = TRUE)
```
* it has to be noted that this can be computationally expensive and depending on the use case, the differences are subtle
---
# Using Sentences in CQP Queries
<table>
<caption>First five Query Matches in GermaParl2, 15th Legislative Period</caption>
<thead>
<tr>
<th style="text-align:left;"> query </th>
<th style="text-align:left;"> match </th>
<th style="text-align:right;"> count </th>
<th style="text-align:right;"> share </th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left;"> &quot;Bundesministerium.*&quot; []{1,5} [xpos = &quot;NN&quot;] within s </td>
<td style="text-align:left;"> Bundesministeriums für Wirtschaft </td>
<td style="text-align:right;"> 84 </td>
<td style="text-align:right;"> 6.78 </td>
</tr>
<tr>
<td style="text-align:left;"> &quot;Bundesministerium.*&quot; []{1,5} [xpos = &quot;NN&quot;] within s </td>
<td style="text-align:left;"> Bundesministeriums für Verkehr </td>
<td style="text-align:right;"> 71 </td>
<td style="text-align:right;"> 5.73 </td>
</tr>
<tr>
<td style="text-align:left;"> &quot;Bundesministerium.*&quot; []{1,5} [xpos = &quot;NN&quot;] within s </td>
<td style="text-align:left;"> Bundesministeriums des Innern </td>
<td style="text-align:right;"> 67 </td>
<td style="text-align:right;"> 5.41 </td>
</tr>
<tr>
<td style="text-align:left;"> &quot;Bundesministerium.*&quot; []{1,5} [xpos = &quot;NN&quot;] within s </td>
<td style="text-align:left;"> Bundesministeriums der Finanzen </td>
<td style="text-align:right;"> 66 </td>
<td style="text-align:right;"> 5.33 </td>
</tr>
<tr>
<td style="text-align:left;"> &quot;Bundesministerium.*&quot; []{1,5} [xpos = &quot;NN&quot;] within s </td>
<td style="text-align:left;"> Bundesministeriums für Gesundheit </td>
<td style="text-align:right;"> 66 </td>
<td style="text-align:right;"> 5.33 </td>
</tr>
<tr>
<td style="text-align:left;"> &quot;Bundesministerium.*&quot; []{1,5} [xpos = &quot;NN&quot;] within s </td>
<td style="text-align:left;"> Bundesministerium des Innern </td>
<td style="text-align:right;"> 61 </td>
<td style="text-align:right;"> 4.92 </td>
</tr>
</tbody>
</table>
---
# Sampling at the sentence level
```r
packageVersion("polmineR")
```
```
## [1] '0.8.9.9001'
```
```r
demsent_ids <- corpus("GERMAPARL2") %>%
hits(query = "Demokratie", s_attribute = "s", decode = FALSE) %>%
as.data.frame() %>%
pull(s)
demsents <- corpus("GERMAPARL2") %>%
subset(s %in% !!demsent_ids) %>%
split(s_attribute = "s") %>%
get_token_stream(p_attribute = "word", collapse = " ")
```
* write it on disk and use it as input for ... whatsoever!
---
# References
Däubler, T., Benoit, K., Mikhaylov, S., & Laver, M. (2012). Natural Sentences as Valid Units for Coded Political Texts. British Journal of Political Science, 42(4), 937–951. http://www.jstor.org/stable/23274173.
</textarea>
<style data-target="print-only">@media screen {.remark-slide-container{display:block;}.remark-slide-scaler{box-shadow:none;}}</style>
<script src="https://remarkjs.com/downloads/remark-latest.min.js"></script>
<script>var slideshow = remark.create({
"countIncrementalSlides": false
});
if (window.HTMLWidgets) slideshow.on('afterShowSlide', function (slide) {
window.dispatchEvent(new Event('resize'));
});
(function(d) {
var s = d.createElement("style"), r = d.querySelector(".remark-slide-scaler");
if (!r) return;
s.type = "text/css"; s.innerHTML = "@page {size: " + r.style.width + " " + r.style.height +"; }";
d.head.appendChild(s);
})(document);
(function(d) {
var el = d.getElementsByClassName("remark-slides-area");
if (!el) return;
var slide, slides = slideshow.getSlides(), els = el[0].children;
for (var i = 1; i < slides.length; i++) {
slide = slides[i];
if (slide.properties.continued === "true" || slide.properties.count === "false") {
els[i - 1].className += ' has-continuation';
}
}
var s = d.createElement("style");
s.type = "text/css"; s.innerHTML = "@media print { .has-continuation { display: none; } }";
d.head.appendChild(s);
})(document);
// delete the temporary CSS (for displaying all slides initially) when the user
// starts to view slides
(function() {
var deleted = false;
slideshow.on('beforeShowSlide', function(slide) {
if (deleted) return;
var sheets = document.styleSheets, node;
for (var i = 0; i < sheets.length; i++) {
node = sheets[i].ownerNode;
if (node.dataset["target"] !== "print-only") continue;
node.parentNode.removeChild(node);
}
deleted = true;
});
})();
// add `data-at-shortcutkeys` attribute to <body> to resolve conflicts with JAWS
// screen reader (see PR #262)
(function(d) {
let res = {};
d.querySelectorAll('.remark-help-content table tr').forEach(tr => {
const t = tr.querySelector('td:nth-child(2)').innerText;
tr.querySelectorAll('td:first-child .key').forEach(key => {
const k = key.innerText;
if (/^[a-z]$/.test(k)) res[k] = t; // must be a single letter (key)
});
});
d.body.setAttribute('data-at-shortcutkeys', JSON.stringify(res));
})(document);
(function() {
"use strict"
// Replace <script> tags in slides area to make them executable
var scripts = document.querySelectorAll(
'.remark-slides-area .remark-slide-container script'
);
if (!scripts.length) return;
for (var i = 0; i < scripts.length; i++) {
var s = document.createElement('script');
var code = document.createTextNode(scripts[i].textContent);
s.appendChild(code);
var scriptAttrs = scripts[i].attributes;
for (var j = 0; j < scriptAttrs.length; j++) {
s.setAttribute(scriptAttrs[j].name, scriptAttrs[j].value);
}
scripts[i].parentElement.replaceChild(s, scripts[i]);
}
})();
(function() {
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
if (/^(https?:)?\/\//.test(links[i].getAttribute('href'))) {
links[i].target = '_blank';
}
}
})();</script>
<script>
slideshow._releaseMath = function(el) {
var i, text, code, codes = el.getElementsByTagName('code');
for (i = 0; i < codes.length;) {
code = codes[i];
if (code.parentNode.tagName !== 'PRE' && code.childElementCount === 0) {
text = code.textContent;
if (/^\\\((.|\s)+\\\)$/.test(text) || /^\\\[(.|\s)+\\\]$/.test(text) ||
/^\$\$(.|\s)+\$\$$/.test(text) ||
/^\\begin\{([^}]+)\}(.|\s)+\\end\{[^}]+\}$/.test(text)) {
code.outerHTML = code.innerHTML; // remove <code></code>
continue;
}
}
i++;
}
};
slideshow._releaseMath(document);
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML';
if (location.protocol !== 'file:' && /^https?:/.test(script.src))
script.src = script.src.replace(/^https?:/, '');
document.getElementsByTagName('head')[0].appendChild(script);
})();
</script>
</body>
</html>