-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnlp.html
More file actions
4556 lines (4480 loc) · 292 KB
/
Copy pathnlp.html
File metadata and controls
4556 lines (4480 loc) · 292 KB
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head>
<meta charset="utf-8">
<meta name="generator" content="quarto-1.9.37">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<title>Natural Language Processing</title>
<style>
/* Default styles provided by pandoc.
** See https://pandoc.org/MANUAL.html#variables-for-html for config info.
*/
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
div.columns{display: flex; gap: min(4vw, 1.5em);}
div.column{flex: auto; overflow-x: auto;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
ul.task-list li input[type="checkbox"] {
width: 0.8em;
margin: 0 0.8em 0.2em -1em; /* quarto-specific, see https://github.com/quarto-dev/quarto-cli/issues/4556 */
vertical-align: middle;
}
/* CSS for syntax highlighting */
html { -webkit-text-size-adjust: 100%; }
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
}
pre.numberSource { margin-left: 3em; padding-left: 4px; }
div.sourceCode
{ }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
</style>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js" integrity="sha384-ZvpUoO/+PpLXR1lu4jmpXWu80pZlYUAfxl5NsBMWOEPSjUn/6Z/hRTt8+pR6L4N2" crossorigin="anonymous"></script><script src="nlp_files/libs/clipboard/clipboard.min.js"></script>
<script src="nlp_files/libs/quarto-html/quarto.js" type="module"></script>
<script src="nlp_files/libs/quarto-html/tabsets/tabsets.js" type="module"></script>
<script src="nlp_files/libs/quarto-html/popper.min.js"></script>
<script src="nlp_files/libs/quarto-html/tippy.umd.min.js"></script>
<script src="nlp_files/libs/quarto-html/anchor.min.js"></script>
<link href="nlp_files/libs/quarto-html/tippy.css" rel="stylesheet">
<link href="nlp_files/libs/quarto-html/quarto-syntax-highlighting-7f8f88aac4f3542376d5c11b86a4c14d.css" rel="stylesheet" id="quarto-text-highlighting-styles">
<script src="nlp_files/libs/bootstrap/bootstrap.min.js"></script>
<link href="nlp_files/libs/bootstrap/bootstrap-icons.css" rel="stylesheet">
<link href="nlp_files/libs/bootstrap/bootstrap-fa30554e3930bdeeaed06393c62b96e8.min.css" rel="stylesheet" append-hash="true" id="quarto-bootstrap" data-mode="light">
<script src="https://cdn.jsdelivr.net/npm/requirejs@2.3.6/require.min.js" integrity="sha384-c9c+LnTbwQ3aujuU7ULEPVvgLs+Fn6fJUvIGTsuu1ZcCf11fiEubah0ttpca4ntM sha384-6V1/AdqZRWk1KAlWbKBlGhN7VG4iE/yAZcO6NZPMF8od0vukrvr0tg4qY6NSrItx" crossorigin="anonymous"></script>
<script type="application/javascript">define('jquery', [],function() {return window.jQuery;})</script>
<script src="https://cdnjs.cloudflare.com/polyfill/v3/polyfill.min.js?features=es6"></script>
<script defer="" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml-full.js" type="text/javascript"></script>
<script type="text/javascript">
const typesetMath = (el) => {
if (window.MathJax) {
// MathJax Typeset
window.MathJax.typeset([el]);
} else if (window.katex) {
// KaTeX Render
var mathElements = el.getElementsByClassName("math");
var macros = [];
for (var i = 0; i < mathElements.length; i++) {
var texText = mathElements[i].firstChild;
if (mathElements[i].tagName == "SPAN" && texText && texText.data) {
window.katex.render(texText.data, mathElements[i], {
displayMode: mathElements[i].classList.contains('display'),
throwOnError: false,
macros: macros,
fleqn: false
});
}
}
}
}
window.Quarto = {
typesetMath
};
</script>
</head>
<body class="fullcontent quarto-light">
<div id="quarto-content" class="page-columns page-rows-contents page-layout-article">
<main class="content" id="quarto-document-content">
<header id="title-block-header" class="quarto-title-block default">
<div class="quarto-title">
<h1 class="title">Natural Language Processing</h1>
</div>
<div class="quarto-title-meta">
</div>
</header>
<section id="natural-language-processing" class="level1">
<h1>Natural Language Processing</h1>
<p>Natural Language Processing (NLP) is the interdisciplinary field that develops computational methods to process, analyze, understand, and generate human language:</p>
<ul>
<li>Using computers to study human language, e.g. measuring language change over time, detecting dialectal variation, evaluating grammatical theories, etc.</li>
<li>Enabling computers to deal with language, e.g. computer translation, summarization, information extraction, comment moderation, etc.</li>
</ul>
<div id="85f4837b" class="cell" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> math</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> collections <span class="im">import</span> Counter</span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> itertools <span class="im">import</span> combinations</span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> pandas <span class="im">as</span> pd</span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> numpy <span class="im">as</span> np</span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> matplotlib.pyplot <span class="im">as</span> plt</span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> mpl_toolkits.mplot3d <span class="im">import</span> Axes3D</span>
<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> matplotlib <span class="im">import</span> cm</span>
<span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> matplotlib.patches <span class="im">as</span> mpatches</span>
<span id="cb1-11"><a href="#cb1-11" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> matplotlib.animation <span class="im">import</span> FuncAnimation</span>
<span id="cb1-12"><a href="#cb1-12" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> IPython.display <span class="im">import</span> HTML</span>
<span id="cb1-13"><a href="#cb1-13" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> seaborn <span class="im">as</span> sns</span>
<span id="cb1-14"><a href="#cb1-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-15"><a href="#cb1-15" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> pathlib <span class="im">import</span> Path</span>
<span id="cb1-16"><a href="#cb1-16" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> requests</span>
<span id="cb1-17"><a href="#cb1-17" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-18"><a href="#cb1-18" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> fitz</span>
<span id="cb1-19"><a href="#cb1-19" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> arxiv, time, requests, os</span>
<span id="cb1-20"><a href="#cb1-20" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> pyreadr</span>
<span id="cb1-21"><a href="#cb1-21" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-22"><a href="#cb1-22" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> nltk</span>
<span id="cb1-23"><a href="#cb1-23" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> nltk.stem <span class="im">import</span> PorterStemmer, WordNetLemmatizer</span>
<span id="cb1-24"><a href="#cb1-24" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> nltk.corpus <span class="im">import</span> stopwords</span>
<span id="cb1-25"><a href="#cb1-25" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-26"><a href="#cb1-26" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> spacy</span>
<span id="cb1-27"><a href="#cb1-27" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> spacy.cli <span class="im">import</span> download</span>
<span id="cb1-28"><a href="#cb1-28" aria-hidden="true" tabindex="-1"></a>download(<span class="st">"en_core_web_sm"</span>)</span>
<span id="cb1-29"><a href="#cb1-29" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-30"><a href="#cb1-30" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> datasets <span class="im">import</span> load_dataset</span>
<span id="cb1-31"><a href="#cb1-31" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-32"><a href="#cb1-32" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> torch</span>
<span id="cb1-33"><a href="#cb1-33" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> torch.nn <span class="im">as</span> nn</span>
<span id="cb1-34"><a href="#cb1-34" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> torch.nn.functional <span class="im">as</span> F</span>
<span id="cb1-35"><a href="#cb1-35" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> torch.utils.data <span class="im">import</span> DataLoader, TensorDataset</span>
<span id="cb1-36"><a href="#cb1-36" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> torchviz <span class="im">import</span> make_dot</span>
<span id="cb1-37"><a href="#cb1-37" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> torchview <span class="im">import</span> draw_graph</span>
<span id="cb1-38"><a href="#cb1-38" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-39"><a href="#cb1-39" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> gensim.models <span class="im">import</span> Word2Vec</span>
<span id="cb1-40"><a href="#cb1-40" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> gensim.downloader <span class="im">as</span> api</span>
<span id="cb1-41"><a href="#cb1-41" aria-hidden="true" tabindex="-1"></a>w2v_pretrained_model <span class="op">=</span> api.load(<span class="st">'word2vec-google-news-300'</span>)</span>
<span id="cb1-42"><a href="#cb1-42" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-43"><a href="#cb1-43" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> editdistance</span>
<span id="cb1-44"><a href="#cb1-44" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-45"><a href="#cb1-45" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> PIL <span class="im">import</span> Image</span>
<span id="cb1-46"><a href="#cb1-46" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> io <span class="im">import</span> BytesIO</span>
<span id="cb1-47"><a href="#cb1-47" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> easyocr</span>
<span id="cb1-48"><a href="#cb1-48" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-49"><a href="#cb1-49" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> unicodedata</span>
<span id="cb1-50"><a href="#cb1-50" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> re</span>
<span id="cb1-51"><a href="#cb1-51" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-52"><a href="#cb1-52" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> sklearn.feature_extraction.text <span class="im">import</span> TfidfVectorizer, CountVectorizer</span>
<span id="cb1-53"><a href="#cb1-53" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> sklearn.metrics.pairwise <span class="im">import</span> cosine_similarity</span>
<span id="cb1-54"><a href="#cb1-54" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> sklearn.decomposition <span class="im">import</span> LatentDirichletAllocation</span>
<span id="cb1-55"><a href="#cb1-55" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> sklearn.cluster <span class="im">import</span> KMeans</span>
<span id="cb1-56"><a href="#cb1-56" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> sklearn.decomposition <span class="im">import</span> PCA</span>
<span id="cb1-57"><a href="#cb1-57" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> sklearn.manifold <span class="im">import</span> TSNE</span>
<span id="cb1-58"><a href="#cb1-58" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> sklearn.preprocessing <span class="im">import</span> normalize</span>
<span id="cb1-59"><a href="#cb1-59" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> sklearn.linear_model <span class="im">import</span> LogisticRegression</span>
<span id="cb1-60"><a href="#cb1-60" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> sklearn.model_selection <span class="im">import</span> cross_val_score</span>
<span id="cb1-61"><a href="#cb1-61" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-62"><a href="#cb1-62" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> sentence_transformers <span class="im">import</span> SentenceTransformer</span>
<span id="cb1-63"><a href="#cb1-63" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-64"><a href="#cb1-64" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> bs4 <span class="im">import</span> BeautifulSoup</span>
<span id="cb1-65"><a href="#cb1-65" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-66"><a href="#cb1-66" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> tokenizers <span class="im">import</span> Tokenizer</span>
<span id="cb1-67"><a href="#cb1-67" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> tokenizers <span class="im">import</span> decoders</span>
<span id="cb1-68"><a href="#cb1-68" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> tokenizers.models <span class="im">import</span> BPE</span>
<span id="cb1-69"><a href="#cb1-69" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> tokenizers.trainers <span class="im">import</span> BpeTrainer</span>
<span id="cb1-70"><a href="#cb1-70" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> tokenizers.pre_tokenizers <span class="im">import</span> Whitespace</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-stdout">
<div class="ansi-escaped-output">
<pre>Collecting en-core-web-sm==3.8.0
Downloading https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.8.0/en_core_web_sm-3.8.0-py3-none-any.whl (12.8 MB)
<span style="color:rgb(58,58,58)">━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━</span> <span class="ansi-green-fg">0.0/12.8 MB</span> <span class="ansi-red-fg">?</span> eta <span class="ansi-cyan-fg">-:--:--</span>
<span style="color:rgb(114,156,31)">━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━</span> <span class="ansi-green-fg">12.8/12.8 MB</span> <span class="ansi-red-fg">93.3 MB/s</span> <span class="ansi-yellow-fg">0:00:00</span>
<span class="ansi-green-fg">✔ Download and installation successful</span>
You can now load the package via spacy.load('en_core_web_sm')
<span class="ansi-yellow-fg">⚠ Restart to reload dependencies</span>
If you are in a Jupyter or Colab notebook, you may need to restart Python in
order to load all the package's dependencies. You can do this by selecting the
'Restart kernel' or 'Restart runtime' option.
</pre>
</div>
</div>
</div>
<section id="outline" class="level2">
<h2 class="anchored" data-anchor-id="outline">Outline</h2>
<ol type="1">
<li>Introduction to handling text data</li>
<li>Intuition about “AI”</li>
<li>Practical applications for social sciences</li>
</ol>
<p>We are going to use mostly two corpora of text:</p>
<ul>
<li>Economics pre-print papers from arXiv</li>
<li>US presidents inaugural speeches</li>
</ul>
<div id="3bd3c674" class="cell" data-execution_count="2">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a>query <span class="op">=</span> <span class="st">"cat:econ.GN"</span> </span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>target_n <span class="op">=</span> <span class="dv">50</span></span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a>out_dir <span class="op">=</span> <span class="st">"arxiv_papers"</span></span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a>os.makedirs(out_dir, exist_ok<span class="op">=</span><span class="va">True</span>)</span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a>search <span class="op">=</span> arxiv.Search(query<span class="op">=</span>query, max_results<span class="op">=</span><span class="va">None</span>, sort_by<span class="op">=</span>arxiv.SortCriterion.SubmittedDate)</span>
<span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-8"><a href="#cb2-8" aria-hidden="true" tabindex="-1"></a>downloaded <span class="op">=</span> <span class="dv">0</span> <span class="co"># 0</span></span>
<span id="cb2-9"><a href="#cb2-9" aria-hidden="true" tabindex="-1"></a><span class="cf">for</span> result <span class="kw">in</span> search.results():</span>
<span id="cb2-10"><a href="#cb2-10" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> downloaded <span class="op">>=</span> target_n:</span>
<span id="cb2-11"><a href="#cb2-11" aria-hidden="true" tabindex="-1"></a> <span class="cf">break</span></span>
<span id="cb2-12"><a href="#cb2-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-13"><a href="#cb2-13" aria-hidden="true" tabindex="-1"></a> arxiv_id <span class="op">=</span> result.get_short_id()</span>
<span id="cb2-14"><a href="#cb2-14" aria-hidden="true" tabindex="-1"></a> pdf_url <span class="op">=</span> result.pdf_url</span>
<span id="cb2-15"><a href="#cb2-15" aria-hidden="true" tabindex="-1"></a> filename <span class="op">=</span> os.path.join(out_dir, <span class="ss">f"</span><span class="sc">{</span>arxiv_id<span class="sc">}</span><span class="ss">.pdf"</span>)</span>
<span id="cb2-16"><a href="#cb2-16" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-17"><a href="#cb2-17" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> <span class="kw">not</span> os.path.exists(filename):</span>
<span id="cb2-18"><a href="#cb2-18" aria-hidden="true" tabindex="-1"></a> r <span class="op">=</span> requests.get(pdf_url, stream<span class="op">=</span><span class="va">True</span>)</span>
<span id="cb2-19"><a href="#cb2-19" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> r.status_code <span class="op">==</span> <span class="dv">200</span>:</span>
<span id="cb2-20"><a href="#cb2-20" aria-hidden="true" tabindex="-1"></a> <span class="cf">with</span> <span class="bu">open</span>(filename, <span class="st">"wb"</span>) <span class="im">as</span> f:</span>
<span id="cb2-21"><a href="#cb2-21" aria-hidden="true" tabindex="-1"></a> <span class="cf">for</span> chunk <span class="kw">in</span> r.iter_content(chunk_size<span class="op">=</span><span class="dv">1024</span><span class="op">*</span><span class="dv">1024</span>):</span>
<span id="cb2-22"><a href="#cb2-22" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> chunk:</span>
<span id="cb2-23"><a href="#cb2-23" aria-hidden="true" tabindex="-1"></a> f.write(chunk)</span>
<span id="cb2-24"><a href="#cb2-24" aria-hidden="true" tabindex="-1"></a> downloaded <span class="op">+=</span> <span class="dv">1</span></span>
<span id="cb2-25"><a href="#cb2-25" aria-hidden="true" tabindex="-1"></a> time.sleep(<span class="dv">3</span>)</span>
<span id="cb2-26"><a href="#cb2-26" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-27"><a href="#cb2-27" aria-hidden="true" tabindex="-1"></a>papers <span class="op">=</span> {}</span>
<span id="cb2-28"><a href="#cb2-28" aria-hidden="true" tabindex="-1"></a><span class="cf">for</span> fname <span class="kw">in</span> os.listdir(out_dir):</span>
<span id="cb2-29"><a href="#cb2-29" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> fname.endswith(<span class="st">".pdf"</span>):</span>
<span id="cb2-30"><a href="#cb2-30" aria-hidden="true" tabindex="-1"></a> fpath <span class="op">=</span> os.path.join(out_dir, fname)</span>
<span id="cb2-31"><a href="#cb2-31" aria-hidden="true" tabindex="-1"></a> <span class="cf">with</span> <span class="bu">open</span>(fpath, <span class="st">"rb"</span>) <span class="im">as</span> f:</span>
<span id="cb2-32"><a href="#cb2-32" aria-hidden="true" tabindex="-1"></a> papers[fname] <span class="op">=</span> f.read()</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-stderr">
<pre><code>/tmp/ipykernel_10194/4149224177.py:9: DeprecationWarning: The 'Search.results' method is deprecated, use 'Client.results' instead
for result in search.results():</code></pre>
</div>
</div>
<div id="57a0ebbb" class="cell" data-execution_count="3">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a>fname, papers[fname][<span class="dv">0</span>:<span class="dv">500</span>] <span class="co"># pdf is not raw text! It's a layout format: it stores instructions like "draw glyph 'A' at coordinates (72, 540)".</span></span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display" data-execution_count="66">
<pre><code>('2603.21874v1.pdf',
b'%PDF-1.7\n%\xbf\xf7\xa2\xfe\n1 0 obj\n<< /Metadata 3 0 R /Names 4 0 R /OpenAction 5 0 R /Outlines 6 0 R /PageMode /UseOutlines /Pages 7 0 R /Type /Catalog >>\nendobj\n2 0 obj\n<< /Author (Ian Crawford; Carl-Emil Pless) /Creator (arXiv GenPDF \\(tex2pdf:a6404ea\\)) /DOI (https://doi.org/10.48550/arXiv.2603.21874) /License (http://arxiv.org/licenses/nonexclusive-distrib/1.0/) /PTEX.Fullbanner (This is pdfTeX, Version 3.141592653-2.6-1.40.28 \\(TeX Live 2025\\) kpathsea version 6.4.1) /Producer (pikepdf 8.15.1) /Title (')</code></pre>
</div>
</div>
<div id="c7e12fd6" class="cell" data-execution_count="4">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a>nltk.download(<span class="st">'inaugural'</span>)</span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> nltk.corpus <span class="im">import</span> inaugural</span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-5"><a href="#cb6-5" aria-hidden="true" tabindex="-1"></a>us <span class="op">=</span> pd.DataFrame([</span>
<span id="cb6-6"><a href="#cb6-6" aria-hidden="true" tabindex="-1"></a> {</span>
<span id="cb6-7"><a href="#cb6-7" aria-hidden="true" tabindex="-1"></a> <span class="st">"year"</span>: <span class="bu">int</span>(parts[<span class="dv">0</span>]),</span>
<span id="cb6-8"><a href="#cb6-8" aria-hidden="true" tabindex="-1"></a> <span class="st">"speaker"</span>: parts[<span class="dv">1</span>],</span>
<span id="cb6-9"><a href="#cb6-9" aria-hidden="true" tabindex="-1"></a> <span class="st">"text"</span>: inaugural.raw(fid),</span>
<span id="cb6-10"><a href="#cb6-10" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb6-11"><a href="#cb6-11" aria-hidden="true" tabindex="-1"></a> <span class="cf">for</span> fid <span class="kw">in</span> inaugural.fileids()</span>
<span id="cb6-12"><a href="#cb6-12" aria-hidden="true" tabindex="-1"></a> <span class="cf">for</span> parts <span class="kw">in</span> [fid.replace(<span class="st">'.txt'</span>, <span class="st">''</span>).split(<span class="st">'-'</span>, <span class="dv">1</span>)]</span>
<span id="cb6-13"><a href="#cb6-13" aria-hidden="true" tabindex="-1"></a>])</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-stderr">
<pre><code>[nltk_data] Downloading package inaugural to /home/onyxia/nltk_data...
[nltk_data] Package inaugural is already up-to-date!</code></pre>
</div>
</div>
<div id="2c639aee" class="cell" data-execution_count="5">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a>us[<span class="dv">0</span>:<span class="dv">20</span>]</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display" data-execution_count="68">
<div>
<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">year</th>
<th data-quarto-table-cell-role="th">speaker</th>
<th data-quarto-table-cell-role="th">text</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">0</th>
<td>1789</td>
<td>Washington</td>
<td>Fellow-Citizens of the Senate and of the House...</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">1</th>
<td>1793</td>
<td>Washington</td>
<td>Fellow citizens, I am again called upon by the...</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">2</th>
<td>1797</td>
<td>Adams</td>
<td>When it was first perceived, in early times, t...</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">3</th>
<td>1801</td>
<td>Jefferson</td>
<td>Friends and Fellow Citizens:\n\nCalled upon to...</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">4</th>
<td>1805</td>
<td>Jefferson</td>
<td>Proceeding, fellow citizens, to that qualifica...</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">5</th>
<td>1809</td>
<td>Madison</td>
<td>Unwilling to depart from examples of the most ...</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">6</th>
<td>1813</td>
<td>Madison</td>
<td>About to add the solemnity of an oath to the o...</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">7</th>
<td>1817</td>
<td>Monroe</td>
<td>I should be destitute of feeling if I was not ...</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">8</th>
<td>1821</td>
<td>Monroe</td>
<td>Fellow citizens, I shall not attempt to descri...</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">9</th>
<td>1825</td>
<td>Adams</td>
<td>In compliance with an usage coeval with the ex...</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">10</th>
<td>1829</td>
<td>Jackson</td>
<td>Fellow citizens, about to undertake the arduou...</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">11</th>
<td>1833</td>
<td>Jackson</td>
<td>Fellow citizens, the will of the American peop...</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">12</th>
<td>1837</td>
<td>VanBuren</td>
<td>Fellow citizens: The practice of all my predec...</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">13</th>
<td>1841</td>
<td>Harrison</td>
<td>Called from a retirement which I had supposed ...</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">14</th>
<td>1845</td>
<td>Polk</td>
<td>Fellow citizens, without solicitation on my pa...</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">15</th>
<td>1849</td>
<td>Taylor</td>
<td>Elected by the American people to the highest ...</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">16</th>
<td>1853</td>
<td>Pierce</td>
<td>My Countrymen, It a relief to feel that no hea...</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">17</th>
<td>1857</td>
<td>Buchanan</td>
<td>Fellow citizens, I appear before you this day ...</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">18</th>
<td>1861</td>
<td>Lincoln</td>
<td>Fellow-Citizens of the United States: In compl...</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">19</th>
<td>1865</td>
<td>Lincoln</td>
<td>Fellow-Countrymen:\n\nAt this second appearing...</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</section>
<section id="making-raw-data-useable" class="level2">
<h2 class="anchored" data-anchor-id="making-raw-data-useable">Making raw data useable</h2>
<p>Text data come in a variety of formats, e.g. PDF, images (scans), JSON, XML…</p>
<p>There is usually a lot of work needed to make raw data useable.</p>
<p>Some examples:</p>
<ul>
<li>PDF is a layout format, describing where different elements should go. It contains both text, images, and metadata.</li>
</ul>
<div id="e107c69a" class="cell" data-execution_count="6">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a>papers_text <span class="op">=</span> {fname: <span class="st">"</span><span class="ch">\n</span><span class="st">"</span>.join(page.get_text() <span class="cf">for</span> page <span class="kw">in</span> fitz.<span class="bu">open</span>(stream<span class="op">=</span>content, filetype<span class="op">=</span><span class="st">"pdf"</span>)) <span class="cf">for</span> fname, content <span class="kw">in</span> papers.items()}</span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>((papers[fname][:<span class="dv">100</span>]), <span class="st">'</span><span class="ch">\n\n</span><span class="st">'</span>, papers_text[fname][:<span class="dv">100</span>])</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-stdout">
<pre><code>b'%PDF-1.7\n%\xbf\xf7\xa2\xfe\n1 0 obj\n<< /Metadata 3 0 R /Names 4 0 R /OpenAction 5 0 R /Outlines 6 0 R /PageMode /'
Does Anxiety Improve Economic
Decision-Making?
Ian Crawford∗
Carl-Emil Pless†
March 24, 2026
We stud</code></pre>
</div>
</div>
<ul>
<li>Web scrapping (see previous classes)</li>
</ul>
<div id="2baaa5e6" class="cell" data-execution_count="7">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a>url <span class="op">=</span> <span class="st">"https://www.theguardian.com"</span></span>
<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a>headers <span class="op">=</span> {<span class="st">"User-Agent"</span>: <span class="st">"Mozilla/5.0 (educational-scraper)"</span>}</span>
<span id="cb11-3"><a href="#cb11-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-4"><a href="#cb11-4" aria-hidden="true" tabindex="-1"></a>resp <span class="op">=</span> requests.get(url, headers<span class="op">=</span>headers, timeout<span class="op">=</span><span class="dv">10</span>)</span>
<span id="cb11-5"><a href="#cb11-5" aria-hidden="true" tabindex="-1"></a>resp.raise_for_status()</span>
<span id="cb11-6"><a href="#cb11-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-7"><a href="#cb11-7" aria-hidden="true" tabindex="-1"></a><span class="co"># Common pitfall: declared vs actual encoding</span></span>
<span id="cb11-8"><a href="#cb11-8" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="ss">f"Declared encoding (headers): </span><span class="sc">{</span>resp<span class="sc">.</span>encoding<span class="sc">}</span><span class="ss">"</span>)</span>
<span id="cb11-9"><a href="#cb11-9" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="ss">f"Detected encoding (content): </span><span class="sc">{</span>resp<span class="sc">.</span>apparent_encoding<span class="sc">}</span><span class="ss">"</span>)</span>
<span id="cb11-10"><a href="#cb11-10" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-11"><a href="#cb11-11" aria-hidden="true" tabindex="-1"></a><span class="co"># Force the correct encoding if needed</span></span>
<span id="cb11-12"><a href="#cb11-12" aria-hidden="true" tabindex="-1"></a>resp.encoding <span class="op">=</span> resp.apparent_encoding</span>
<span id="cb11-13"><a href="#cb11-13" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-14"><a href="#cb11-14" aria-hidden="true" tabindex="-1"></a>soup <span class="op">=</span> BeautifulSoup(resp.text, <span class="st">"html.parser"</span>)</span>
<span id="cb11-15"><a href="#cb11-15" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-16"><a href="#cb11-16" aria-hidden="true" tabindex="-1"></a><span class="co"># Extract article headlines</span></span>
<span id="cb11-17"><a href="#cb11-17" aria-hidden="true" tabindex="-1"></a>headlines <span class="op">=</span> [h.get_text(strip<span class="op">=</span><span class="va">True</span>) <span class="cf">for</span> h <span class="kw">in</span> soup.find_all([<span class="st">"h1"</span>, <span class="st">"h2"</span>, <span class="st">"h3"</span>])]</span>
<span id="cb11-18"><a href="#cb11-18" aria-hidden="true" tabindex="-1"></a><span class="cf">for</span> h <span class="kw">in</span> headlines[<span class="dv">0</span>:<span class="dv">10</span>]:</span>
<span id="cb11-19"><a href="#cb11-19" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(<span class="ss">f"</span><span class="sc">{</span>h[:<span class="dv">80</span>]<span class="sc">}</span><span class="ss">"</span>)</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-stdout">
<pre><code>Declared encoding (headers): UTF-8
Detected encoding (content): utf-8
Paul Taylordouble quotation markA crowded field could gift French election to fa
InterviewPreston looks back at a tumultuous career
InterviewColombia’s VP blames racism for years of frustration
Today in FocusWhen the ‘Dubai dream’ goes wrong
TelevisionGrayson Perry's insights into AI are mindblowing
Analysisdouble quotation markIs this how you win things? Arsenal hope so
News
Middle East crisis liveNetanyahu ‘to speak to Lebanese leader leader today’ but
Middle East crisisUS and Iran in indirect talks to extend two-week ceasefire
AnalysisTrump needs a better Iran deal than Obama’s – but faces major hurdles</code></pre>
</div>
</div>
<ul>
<li>OCR</li>
</ul>
<p>Optical Character Recognition (OCR) converts images of printed text to machine-readable strings. Handwritten Text Recognition (HTR) handles manuscripts and handwritten records.</p>
<p>Quality is measured by two metrics:</p>
<ul>
<li>Character Error Rate (CER): fraction of characters incorrectly transcribed</li>
<li>Word Error Rate (WER): fraction of words containing at least one error</li>
</ul>
<div id="8d14c4e7" class="cell" data-execution_count="8">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a>image_url <span class="op">=</span> <span class="st">"https://upload.wikimedia.org/wikipedia/commons/d/dd/The_universal_declaration_of_human_rights_10_December_1948.jpg"</span></span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb13-3"><a href="#cb13-3" aria-hidden="true" tabindex="-1"></a>headers <span class="op">=</span> {</span>
<span id="cb13-4"><a href="#cb13-4" aria-hidden="true" tabindex="-1"></a> <span class="st">"User-Agent"</span>: <span class="st">"MyOCRScript/1.0 (https://test.com/; <mailto:contact@test.com>)"</span>,</span>
<span id="cb13-5"><a href="#cb13-5" aria-hidden="true" tabindex="-1"></a>}</span>
<span id="cb13-6"><a href="#cb13-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb13-7"><a href="#cb13-7" aria-hidden="true" tabindex="-1"></a>session <span class="op">=</span> requests.Session()</span>
<span id="cb13-8"><a href="#cb13-8" aria-hidden="true" tabindex="-1"></a>resp <span class="op">=</span> session.get(image_url, headers<span class="op">=</span>headers, timeout<span class="op">=</span><span class="dv">10</span>)</span>
<span id="cb13-9"><a href="#cb13-9" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb13-10"><a href="#cb13-10" aria-hidden="true" tabindex="-1"></a>resp.raise_for_status() <span class="co"># will raise if still a 4xx/5xx</span></span>
<span id="cb13-11"><a href="#cb13-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb13-12"><a href="#cb13-12" aria-hidden="true" tabindex="-1"></a>img <span class="op">=</span> Image.<span class="bu">open</span>(BytesIO(resp.content))</span>
<span id="cb13-13"><a href="#cb13-13" aria-hidden="true" tabindex="-1"></a>img_array <span class="op">=</span> np.array(img)</span>
<span id="cb13-14"><a href="#cb13-14" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="ss">f"Shape: </span><span class="sc">{</span>img_array<span class="sc">.</span>shape<span class="sc">}</span><span class="ss">, dtype: </span><span class="sc">{</span>img_array<span class="sc">.</span>dtype<span class="sc">}</span><span class="ss">"</span>)</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-stdout">
<pre><code>Shape: (2698, 2000, 3), dtype: uint8</code></pre>
</div>
</div>
<p>A raster image is an array of Red, Green, Blue values (see previous class on raster data for geography).</p>
<div id="7dabcb30" class="cell" data-execution_count="9">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a>reader <span class="op">=</span> easyocr.Reader([<span class="st">'en'</span>]) </span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a>result <span class="op">=</span> reader.readtext(img)</span>
<span id="cb15-3"><a href="#cb15-3" aria-hidden="true" tabindex="-1"></a>text <span class="op">=</span> <span class="st">' '</span>.join([detection[<span class="dv">1</span>] <span class="cf">for</span> detection <span class="kw">in</span> result])</span>
<span id="cb15-4"><a href="#cb15-4" aria-hidden="true" tabindex="-1"></a>text[<span class="dv">0</span>:<span class="dv">100</span>]</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display" data-execution_count="72">
<pre><code>'THE UUNIVERSAL DECLARATION OF Human WIIEREAS recognition of the inherent dignity and of the equal an'</code></pre>
</div>
</div>
<div id="e05935cd" class="cell" data-execution_count="10">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a>fig, (ax_img, ax_txt) <span class="op">=</span> plt.subplots(<span class="dv">1</span>, <span class="dv">2</span>)</span>
<span id="cb17-2"><a href="#cb17-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb17-3"><a href="#cb17-3" aria-hidden="true" tabindex="-1"></a>ax_img.imshow(img)</span>
<span id="cb17-4"><a href="#cb17-4" aria-hidden="true" tabindex="-1"></a>ax_img.axis(<span class="st">"off"</span>)</span>
<span id="cb17-5"><a href="#cb17-5" aria-hidden="true" tabindex="-1"></a>ax_img.set_title(<span class="st">"Original Image"</span>)</span>
<span id="cb17-6"><a href="#cb17-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb17-7"><a href="#cb17-7" aria-hidden="true" tabindex="-1"></a>ax_txt.text(</span>
<span id="cb17-8"><a href="#cb17-8" aria-hidden="true" tabindex="-1"></a> <span class="fl">0.05</span>, <span class="fl">0.95</span>, text[<span class="dv">0</span>:<span class="dv">200</span>] <span class="op">+</span> <span class="st">"..."</span>,</span>
<span id="cb17-9"><a href="#cb17-9" aria-hidden="true" tabindex="-1"></a> transform<span class="op">=</span>ax_txt.transAxes,</span>
<span id="cb17-10"><a href="#cb17-10" aria-hidden="true" tabindex="-1"></a> fontsize<span class="op">=</span><span class="dv">10</span>,</span>
<span id="cb17-11"><a href="#cb17-11" aria-hidden="true" tabindex="-1"></a> verticalalignment<span class="op">=</span><span class="st">"top"</span>,</span>
<span id="cb17-12"><a href="#cb17-12" aria-hidden="true" tabindex="-1"></a> family<span class="op">=</span><span class="st">"monospace"</span>,</span>
<span id="cb17-13"><a href="#cb17-13" aria-hidden="true" tabindex="-1"></a> wrap<span class="op">=</span><span class="va">True</span>,</span>
<span id="cb17-14"><a href="#cb17-14" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb17-15"><a href="#cb17-15" aria-hidden="true" tabindex="-1"></a>ax_txt.axis(<span class="st">"off"</span>)</span>
<span id="cb17-16"><a href="#cb17-16" aria-hidden="true" tabindex="-1"></a>ax_txt.set_title(<span class="st">"OCR Output"</span>)</span>
<span id="cb17-17"><a href="#cb17-17" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb17-18"><a href="#cb17-18" aria-hidden="true" tabindex="-1"></a>plt.tight_layout()</span>
<span id="cb17-19"><a href="#cb17-19" aria-hidden="true" tabindex="-1"></a>plt.show()</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="nlp_files/figure-html/cell-11-output-1.png" width="675" height="470" class="figure-img"></p>
</figure>
</div>
</div>
</div>
<div id="2e60d0cf" class="cell" data-execution_count="11">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb18"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> extract_udhr_text(html: <span class="bu">str</span>) <span class="op">-></span> <span class="bu">str</span>:</span>
<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a> html <span class="op">=</span> re.sub(<span class="vs">r"<script</span><span class="pp">[^>]</span><span class="op">*</span><span class="vs">></span><span class="dv">.</span><span class="op">*?</span><span class="vs"></script>"</span>, <span class="st">""</span>, html, flags<span class="op">=</span>re.DOTALL)</span>
<span id="cb18-3"><a href="#cb18-3" aria-hidden="true" tabindex="-1"></a> html <span class="op">=</span> re.sub(<span class="vs">r"<style</span><span class="pp">[^>]</span><span class="op">*</span><span class="vs">></span><span class="dv">.</span><span class="op">*?</span><span class="vs"></style>"</span>, <span class="st">""</span>, html, flags<span class="op">=</span>re.DOTALL)</span>
<span id="cb18-4"><a href="#cb18-4" aria-hidden="true" tabindex="-1"></a> text <span class="op">=</span> re.sub(<span class="vs">r"<</span><span class="pp">[^>]</span><span class="op">+</span><span class="vs">>"</span>, <span class="st">" "</span>, html)</span>
<span id="cb18-5"><a href="#cb18-5" aria-hidden="true" tabindex="-1"></a> text <span class="op">=</span> re.sub(<span class="vs">r"</span><span class="dv">\s</span><span class="op">+</span><span class="vs">"</span>, <span class="st">" "</span>, text).strip()</span>
<span id="cb18-6"><a href="#cb18-6" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> unicodedata.normalize(<span class="st">"NFC"</span>, text)</span>
<span id="cb18-7"><a href="#cb18-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb18-8"><a href="#cb18-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb18-9"><a href="#cb18-9" aria-hidden="true" tabindex="-1"></a>resp <span class="op">=</span> session.get(</span>
<span id="cb18-10"><a href="#cb18-10" aria-hidden="true" tabindex="-1"></a> <span class="st">"https://en.wikisource.org/wiki/Universal_Declaration_of_Human_Rights"</span>,</span>
<span id="cb18-11"><a href="#cb18-11" aria-hidden="true" tabindex="-1"></a> headers<span class="op">=</span>headers, timeout<span class="op">=</span><span class="dv">10</span></span>
<span id="cb18-12"><a href="#cb18-12" aria-hidden="true" tabindex="-1"></a> )</span>
<span id="cb18-13"><a href="#cb18-13" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb18-14"><a href="#cb18-14" aria-hidden="true" tabindex="-1"></a>resp.raise_for_status()</span>
<span id="cb18-15"><a href="#cb18-15" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb18-16"><a href="#cb18-16" aria-hidden="true" tabindex="-1"></a>ground_truth <span class="op">=</span> extract_udhr_text(resp.text)</span>
<span id="cb18-17"><a href="#cb18-17" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb18-18"><a href="#cb18-18" aria-hidden="true" tabindex="-1"></a>ground_truth[<span class="dv">0</span>:<span class="dv">100</span>]</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display" data-execution_count="74">
<pre><code>'Universal Declaration of Human Rights - Wikisource, the free online library Jump to content Main men'</code></pre>
</div>
</div>
<div id="02dbc134" class="cell" data-execution_count="12">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb20"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a>ground_truth_split <span class="op">=</span> ground_truth.split()</span>
<span id="cb20-2"><a href="#cb20-2" aria-hidden="true" tabindex="-1"></a>text_split <span class="op">=</span> text.split()</span>
<span id="cb20-3"><a href="#cb20-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb20-4"><a href="#cb20-4" aria-hidden="true" tabindex="-1"></a>editdistance.<span class="bu">eval</span>(ground_truth_split, text_split) <span class="op">/</span> <span class="bu">len</span>(ground_truth_split)</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display" data-execution_count="75">
<pre><code>0.8840328861964517</code></pre>
</div>
</div>
<ul>
<li>Encodings</li>
</ul>
<p>Computers store data as 0s & 1s.</p>
<p>Character encodings map 0s/1s to actual characters.</p>
<p>There are many different encodings; you should almost always convert to Unicode normalisation if your corpora span languages or historical periods, or if you pool documents from different sources which may have used different encodings.</p>
<p>Failing to normalise before tokenisation produces duplicate tokens, incorrect frequency counts, and silent data loss.</p>
<div id="61c0ff28" class="cell" data-execution_count="13">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb22"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb22-1"><a href="#cb22-1" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">"u</span><span class="ch">\u0308</span><span class="st">"</span>)</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-stdout">
<pre><code>ü</code></pre>
</div>
</div>
<div id="95865b1b" class="cell" data-execution_count="14">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb24"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb24-1"><a href="#cb24-1" aria-hidden="true" tabindex="-1"></a><span class="co">"ü"</span> <span class="op">==</span> <span class="st">"u</span><span class="ch">\u0308</span><span class="st">"</span></span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display" data-execution_count="77">
<pre><code>False</code></pre>
</div>
</div>
<div id="d0f5aae1" class="cell" data-execution_count="15">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb26"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb26-1"><a href="#cb26-1" aria-hidden="true" tabindex="-1"></a>unicodedata.normalize(<span class="st">"NFC"</span>, <span class="st">"u</span><span class="ch">\u0308</span><span class="st">"</span>) <span class="op">==</span> <span class="st">"ü"</span> </span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display" data-execution_count="78">
<pre><code>True</code></pre>
</div>
</div>
</section>
<section id="some-basic-processing-tasks-tools" class="level2">
<h2 class="anchored" data-anchor-id="some-basic-processing-tasks-tools">Some basic processing tasks & tools</h2>
<ul>
<li>Regular expressions (REGEX). A regex is a pattern that describes a set of strings. The engine scans input left-to-right, attempting to match the pattern at each position, e.g. to match email adresses, we might want a substring that fits the following pattern:
<ul>
<li>any number of alphanumeric characters and ., _, + or -</li>
<li>followed by @</li>
<li>followed by the domain name (alphanumeric character, dots or hyphen)</li>
<li>followed by a dot .</li>
<li>followed by the TLD (at least two letters)</li>
</ul></li>
</ul>
<p>Note: this does not actually catches <em>all</em> valid email adresses.</p>
<div id="b7a19322" class="cell" data-execution_count="16">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb28"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb28-1"><a href="#cb28-1" aria-hidden="true" tabindex="-1"></a>email_pattern <span class="op">=</span> re.<span class="bu">compile</span>(</span>
<span id="cb28-2"><a href="#cb28-2" aria-hidden="true" tabindex="-1"></a> <span class="vs">r"""</span></span>
<span id="cb28-3"><a href="#cb28-3" aria-hidden="true" tabindex="-1"></a><span class="vs"> </span><span class="kw">(</span><span class="fu">?P<local></span><span class="vs"> </span><span class="pp">[a-zA-Z0-9._+-]</span><span class="op">+</span><span class="kw">)</span><span class="vs"> </span><span class="co"># local part</span></span>
<span id="cb28-4"><a href="#cb28-4" aria-hidden="true" tabindex="-1"></a><span class="vs"> @ </span><span class="co"># literal @</span></span>
<span id="cb28-5"><a href="#cb28-5" aria-hidden="true" tabindex="-1"></a><span class="vs"> </span><span class="kw">(</span><span class="fu">?P<domain></span><span class="vs"> </span><span class="pp">[a-zA-Z0-9.-]</span><span class="op">+</span><span class="kw">)</span><span class="vs"> </span><span class="co"># domain</span></span>
<span id="cb28-6"><a href="#cb28-6" aria-hidden="true" tabindex="-1"></a><span class="vs"> </span><span class="ch">\.</span><span class="vs"> </span><span class="co"># literal dot</span></span>
<span id="cb28-7"><a href="#cb28-7" aria-hidden="true" tabindex="-1"></a><span class="vs"> </span><span class="kw">(</span><span class="fu">?P<tld></span><span class="vs"> </span><span class="pp">[a-zA-Z]</span><span class="op">{2,}</span><span class="kw">)</span><span class="vs"> </span><span class="co"># TLD</span></span>
<span id="cb28-8"><a href="#cb28-8" aria-hidden="true" tabindex="-1"></a><span class="vs"> """</span>,</span>
<span id="cb28-9"><a href="#cb28-9" aria-hidden="true" tabindex="-1"></a> re.VERBOSE</span>
<span id="cb28-10"><a href="#cb28-10" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb28-11"><a href="#cb28-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb28-12"><a href="#cb28-12" aria-hidden="true" tabindex="-1"></a><span class="cf">for</span> fname, text <span class="kw">in</span> <span class="bu">list</span>(papers_text.items())[:<span class="dv">20</span>]:</span>
<span id="cb28-13"><a href="#cb28-13" aria-hidden="true" tabindex="-1"></a> matches <span class="op">=</span> email_pattern.finditer(text <span class="kw">or</span> <span class="st">""</span>)</span>
<span id="cb28-14"><a href="#cb28-14" aria-hidden="true" tabindex="-1"></a> emails <span class="op">=</span> [m.group(<span class="dv">0</span>) <span class="cf">for</span> m <span class="kw">in</span> matches]</span>
<span id="cb28-15"><a href="#cb28-15" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(<span class="ss">f"</span><span class="sc">{</span>fname<span class="sc">}</span><span class="ss"> </span><span class="sc">{</span>emails<span class="sc">}</span><span class="ss">"</span>)</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-stdout">
<pre><code>2604.01933v1.pdf ['szb0288@auburn.edu', 'jnunley@uwlax.edu', 'alan.seals@auburn.edu', 'mingzhou.wang@uga.edu']
2604.01364v1.pdf ['cespinal@eafit.edu.co']
2603.07893v2.pdf ['caitken@uchicago.edu', 'kremermr@uchicago.edu']
2603.12301v1.pdf ['wesley@topos.institute']
2603.15832v1.pdf ['zy.kang@utoronto.ca']
2604.00874v1.pdf ['cashman@mit.edu']
2604.10570v1.pdf ['20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn', '20250612@hhu.edu.cn']
2603.15700v1.pdf ['nandini.maroo@research.iiit.ac.in', 'kavita.vemuri@iiit.ac.in']
2603.12129v1.pdf []
2603.27724v1.pdf ['ertian.chen.19@ucl.ac.uk', 'lichao.chen.17@ucl.ac.uk', 'l.nesheim@ucl.ac.uk']
2603.12128v2.pdf []
2604.11384v1.pdf ['rok.spruk@ef.uni-lj.si']
2604.02875v1.pdf []
2603.26853v1.pdf []
2604.13998v1.pdf ['lev.razumovskiy@ramax.com', 'nikolay.karenin@ramax.com', 'msafro@ramax.com']
2603.29070v2.pdf ['sandro.ambuehl@econ.uzh.ch', 'rbhui@mit.edu', 'heidi.thysen@nhh.no']
2603.09637v1.pdf ['yamaei@seinan-gu.ac.jp', 'ohtake@cider.osaka-u.ac.jp']
2603.16006v1.pdf ['indrefjorden@pm.me']
2603.08603v1.pdf []
2603.21895v1.pdf ['devetak@csh.ac.at', 'antoine.mandel@univ-paris1.fr']</code></pre>
</div>
</div>
<ul>
<li>Tokenization: splitting text into units. Three levels of granularity:
<ul>
<li>Whitespace / rule-based (spaCy, NLTK): splits on spaces and punctuation.</li>
<li>Subword / BPE (Byte Pair Encoding): builds a vocabulary by iteratively merging the most frequent character pairs.</li>
</ul></li>
<li>Normalization:
<ul>
<li>Lemmatization (“organizing” -> “organize”)</li>
<li>Stemming (“organizing” -> “organ”)</li>
<li>Stopword removal</li>
</ul></li>
</ul>
<div id="eb987a3d" class="cell" data-execution_count="17">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb30"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb30-1"><a href="#cb30-1" aria-hidden="true" tabindex="-1"></a>nltk.download(<span class="st">"punkt_tab"</span>, quiet<span class="op">=</span><span class="va">True</span>)</span>
<span id="cb30-2"><a href="#cb30-2" aria-hidden="true" tabindex="-1"></a>nltk.download(<span class="st">"averaged_perceptron_tagger_eng"</span>, quiet<span class="op">=</span><span class="va">True</span>)</span>
<span id="cb30-3"><a href="#cb30-3" aria-hidden="true" tabindex="-1"></a>nltk.download(<span class="st">"wordnet"</span>, quiet<span class="op">=</span><span class="va">True</span>)</span>
<span id="cb30-4"><a href="#cb30-4" aria-hidden="true" tabindex="-1"></a>nltk.download(<span class="st">"stopwords"</span>, quiet<span class="op">=</span><span class="va">True</span>)</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display" data-execution_count="80">
<pre><code>True</code></pre>
</div>
</div>
<div id="6ba63f33" class="cell" data-execution_count="18">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb32"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb32-1"><a href="#cb32-1" aria-hidden="true" tabindex="-1"></a>jfk <span class="op">=</span> us.loc[<span class="dv">43</span>, <span class="st">"text"</span>]</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
</div>
<div id="c7522ec7" class="cell" data-execution_count="19">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb33"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb33-1"><a href="#cb33-1" aria-hidden="true" tabindex="-1"></a>jfk.split()[<span class="dv">0</span>:<span class="dv">20</span>]</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display" data-execution_count="82">
<pre><code>['Vice',
'President',
'Johnson,',
'Mr.',
'Speaker,',
'Mr.',
'Chief',
'Justice,',
'President',
'Eisenhower,',
'Vice',
'President',
'Nixon,',
'President',
'Truman,',
'reverend',
'clergy,',
'fellow',
'citizens,',
'we']</code></pre>
</div>
</div>
<div id="9a8166d5" class="cell" data-execution_count="20">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb35"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb35-1"><a href="#cb35-1" aria-hidden="true" tabindex="-1"></a>nltk_tokens <span class="op">=</span> nltk.word_tokenize(jfk)</span>
<span id="cb35-2"><a href="#cb35-2" aria-hidden="true" tabindex="-1"></a>nltk_tokens[<span class="dv">0</span>:<span class="dv">20</span>]</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display" data-execution_count="83">
<pre><code>['Vice',
'President',
'Johnson',
',',
'Mr.',
'Speaker',
',',
'Mr.',
'Chief',
'Justice',
',',
'President',
'Eisenhower',
',',
'Vice',
'President',
'Nixon',
',',
'President',
'Truman']</code></pre>
</div>
</div>
<div id="362f731f" class="cell" data-execution_count="21">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb37"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb37-1"><a href="#cb37-1" aria-hidden="true" tabindex="-1"></a>stemmer <span class="op">=</span> PorterStemmer()</span>
<span id="cb37-2"><a href="#cb37-2" aria-hidden="true" tabindex="-1"></a>lemmatizer <span class="op">=</span> WordNetLemmatizer()</span>
<span id="cb37-3"><a href="#cb37-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb37-4"><a href="#cb37-4" aria-hidden="true" tabindex="-1"></a>stop_words <span class="op">=</span> <span class="bu">set</span>(stopwords.words(<span class="st">'english'</span>))</span>
<span id="cb37-5"><a href="#cb37-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb37-6"><a href="#cb37-6" aria-hidden="true" tabindex="-1"></a><span class="cf">for</span> w <span class="kw">in</span> nltk_tokens[<span class="dv">150</span>:<span class="dv">175</span>]:</span>
<span id="cb37-7"><a href="#cb37-7" aria-hidden="true" tabindex="-1"></a> is_stop <span class="op">=</span> <span class="st">"✓"</span> <span class="cf">if</span> w.lower() <span class="kw">in</span> stop_words <span class="cf">else</span> <span class="st">""</span></span>
<span id="cb37-8"><a href="#cb37-8" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(<span class="ss">f"</span><span class="sc">{</span>w<span class="sc">:<18}</span><span class="ss"> </span><span class="sc">{</span>stemmer<span class="sc">.</span>stem(w)<span class="sc">:<15}</span><span class="ss"> </span><span class="sc">{</span>lemmatizer<span class="sc">.</span>lemmatize(w, pos<span class="op">=</span><span class="st">'v'</span>)<span class="sc">:<15}</span><span class="ss"> </span><span class="sc">{</span>is_stop<span class="sc">}</span><span class="ss">"</span>)</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-stdout">
<pre><code>, , ,
but but but ✓
from from from ✓
the the the ✓
hand hand hand
of of of ✓
God god God
. . .
We we We ✓
dare dare dare
not not not ✓
forget forget forget
today today today
that that that ✓
we we we ✓
are are be ✓
the the the ✓
heirs heir heirs
of of of ✓
that that that ✓
first first first
revolution revolut revolution
. . .
Let let Let
the the the ✓</code></pre>
</div>
</div>
<p>Application : Zipf’s law</p>
<p>Word frequency follows a power law : <span class="math display">\[f(r) \propto \frac{1}{r^s}\]</span></p>
<p>where <span class="math inline">\(r\)</span> is the frequency rank and <span class="math inline">\(s \approx 1\)</span>. The most frequent word is roughly twice as frequent as the second most frequent, three times the third, and so on.</p>
<p>Note this means there is a massive long tail: most vocabulary items are rare.</p>
<div id="6b29f8c0" class="cell" data-execution_count="22">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb39"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb39-1"><a href="#cb39-1" aria-hidden="true" tabindex="-1"></a>tokens <span class="op">=</span> nltk.word_tokenize(<span class="st">' '</span>.join(papers_text.values()).lower())</span>
<span id="cb39-2"><a href="#cb39-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb39-3"><a href="#cb39-3" aria-hidden="true" tabindex="-1"></a>tokens <span class="op">=</span> [</span>
<span id="cb39-4"><a href="#cb39-4" aria-hidden="true" tabindex="-1"></a> lemmatizer.lemmatize(w, pos<span class="op">=</span><span class="st">'v'</span>)</span>
<span id="cb39-5"><a href="#cb39-5" aria-hidden="true" tabindex="-1"></a> <span class="cf">for</span> w <span class="kw">in</span> tokens</span>
<span id="cb39-6"><a href="#cb39-6" aria-hidden="true" tabindex="-1"></a>]</span>
<span id="cb39-7"><a href="#cb39-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb39-8"><a href="#cb39-8" aria-hidden="true" tabindex="-1"></a>freq <span class="op">=</span> Counter(tokens)</span>
<span id="cb39-9"><a href="#cb39-9" aria-hidden="true" tabindex="-1"></a>ranks <span class="op">=</span> np.arange(<span class="dv">1</span>, <span class="bu">len</span>(freq) <span class="op">+</span> <span class="dv">1</span>)</span>
<span id="cb39-10"><a href="#cb39-10" aria-hidden="true" tabindex="-1"></a>counts <span class="op">=</span> np.array([c <span class="cf">for</span> _, c <span class="kw">in</span> freq.most_common()])</span>
<span id="cb39-11"><a href="#cb39-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb39-12"><a href="#cb39-12" aria-hidden="true" tabindex="-1"></a>log_ranks <span class="op">=</span> np.log(ranks)</span>
<span id="cb39-13"><a href="#cb39-13" aria-hidden="true" tabindex="-1"></a>log_counts <span class="op">=</span> np.log(counts)</span>
<span id="cb39-14"><a href="#cb39-14" aria-hidden="true" tabindex="-1"></a>slope, intercept <span class="op">=</span> np.polyfit(log_ranks, log_counts, <span class="dv">1</span>)</span>
<span id="cb39-15"><a href="#cb39-15" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb39-16"><a href="#cb39-16" aria-hidden="true" tabindex="-1"></a>fig, ax <span class="op">=</span> plt.subplots(figsize<span class="op">=</span>(<span class="dv">9</span>, <span class="dv">5</span>))</span>
<span id="cb39-17"><a href="#cb39-17" aria-hidden="true" tabindex="-1"></a>ax.scatter(log_ranks, log_counts, s<span class="op">=</span><span class="dv">4</span>, alpha<span class="op">=</span><span class="fl">0.4</span>, label<span class="op">=</span><span class="st">'Observed'</span>)</span>
<span id="cb39-18"><a href="#cb39-18" aria-hidden="true" tabindex="-1"></a>ax.plot(log_ranks, slope <span class="op">*</span> log_ranks <span class="op">+</span> intercept, color<span class="op">=</span><span class="st">'crimson'</span>, lw<span class="op">=</span><span class="fl">1.5</span>,</span>
<span id="cb39-19"><a href="#cb39-19" aria-hidden="true" tabindex="-1"></a> label<span class="op">=</span><span class="ss">f'OLS fit slope=</span><span class="sc">{</span>slope<span class="sc">:.2f}</span><span class="ss">'</span>)</span>
<span id="cb39-20"><a href="#cb39-20" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb39-21"><a href="#cb39-21" aria-hidden="true" tabindex="-1"></a>ax.set_xlabel(<span class="st">'log(rank)'</span>)</span>
<span id="cb39-22"><a href="#cb39-22" aria-hidden="true" tabindex="-1"></a>ax.set_ylabel(<span class="st">'log(frequency)'</span>)</span>
<span id="cb39-23"><a href="#cb39-23" aria-hidden="true" tabindex="-1"></a>ax.set_title(<span class="st">"Zipf's Law"</span>)</span>
<span id="cb39-24"><a href="#cb39-24" aria-hidden="true" tabindex="-1"></a>ax.legend()</span>
<span id="cb39-25"><a href="#cb39-25" aria-hidden="true" tabindex="-1"></a>plt.tight_layout()</span>
<span id="cb39-26"><a href="#cb39-26" aria-hidden="true" tabindex="-1"></a>plt.show()</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display">
<div>
<figure class="figure">
<p><img src="nlp_files/figure-html/cell-23-output-1.png" width="854" height="470" class="figure-img"></p>
</figure>
</div>
</div>
</div>
<p>We may need to represent texts as some kind of numerical data structure that would be easier to work with. Examples include:</p>
<ul>
<li>Document term matrix: 1 entry per token, value is number of times the word appear in a given document. We lose word order.</li>
</ul>
<div id="454399e2" class="cell" data-execution_count="23">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb40"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb40-1"><a href="#cb40-1" aria-hidden="true" tabindex="-1"></a>vectorizer <span class="op">=</span> CountVectorizer(stop_words<span class="op">=</span><span class="st">"english"</span>, min_df<span class="op">=</span><span class="dv">1</span>)</span>
<span id="cb40-2"><a href="#cb40-2" aria-hidden="true" tabindex="-1"></a>dtm <span class="op">=</span> vectorizer.fit_transform(us[<span class="st">"text"</span>])</span>
<span id="cb40-3"><a href="#cb40-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb40-4"><a href="#cb40-4" aria-hidden="true" tabindex="-1"></a>df_dtm <span class="op">=</span> pd.DataFrame(</span>
<span id="cb40-5"><a href="#cb40-5" aria-hidden="true" tabindex="-1"></a> dtm.toarray(),</span>
<span id="cb40-6"><a href="#cb40-6" aria-hidden="true" tabindex="-1"></a> columns<span class="op">=</span>vectorizer.get_feature_names_out(),</span>
<span id="cb40-7"><a href="#cb40-7" aria-hidden="true" tabindex="-1"></a> index<span class="op">=</span>[<span class="ss">f"doc_</span><span class="sc">{</span>i<span class="sc">}</span><span class="ss">"</span> <span class="cf">for</span> i <span class="kw">in</span> <span class="bu">range</span>(<span class="bu">len</span>(us))],</span>
<span id="cb40-8"><a href="#cb40-8" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb40-9"><a href="#cb40-9" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="ss">f"Matrix: </span><span class="sc">{</span>dtm<span class="sc">.</span>shape[<span class="dv">0</span>]<span class="sc">}</span><span class="ss"> speeches × </span><span class="sc">{</span>dtm<span class="sc">.</span>shape[<span class="dv">1</span>]<span class="sc">}</span><span class="ss"> tokens"</span>)</span>
<span id="cb40-10"><a href="#cb40-10" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="ss">f"Sparsity: </span><span class="sc">{</span><span class="dv">1</span> <span class="op">-</span> dtm<span class="sc">.</span>nnz <span class="op">/</span> (dtm.shape[<span class="dv">0</span>] <span class="op">*</span> dtm.shape[<span class="dv">1</span>])<span class="sc">:.1%}</span><span class="ch">\n</span><span class="ss">"</span>)</span>
<span id="cb40-11"><a href="#cb40-11" aria-hidden="true" tabindex="-1"></a>df_dtm</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-stdout">
<pre><code>Matrix: 60 speeches × 9139 tokens
Sparsity: 93.1%
</code></pre>
</div>
<div class="cell-output cell-output-display" data-execution_count="86">
<div>
<table class="dataframe caption-top table table-sm table-striped small" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">000</th>
<th data-quarto-table-cell-role="th">100</th>
<th data-quarto-table-cell-role="th">108</th>
<th data-quarto-table-cell-role="th">11</th>
<th data-quarto-table-cell-role="th">120</th>
<th data-quarto-table-cell-role="th">125</th>
<th data-quarto-table-cell-role="th">13</th>
<th data-quarto-table-cell-role="th">14th</th>
<th data-quarto-table-cell-role="th">15th</th>
<th data-quarto-table-cell-role="th">16</th>
<th data-quarto-table-cell-role="th">...</th>
<th data-quarto-table-cell-role="th">young</th>
<th data-quarto-table-cell-role="th">younger</th>
<th data-quarto-table-cell-role="th">youngest</th>
<th data-quarto-table-cell-role="th">youth</th>
<th data-quarto-table-cell-role="th">youthful</th>
<th data-quarto-table-cell-role="th">youâ</th>
<th data-quarto-table-cell-role="th">zeal</th>
<th data-quarto-table-cell-role="th">zealous</th>
<th data-quarto-table-cell-role="th">zealously</th>
<th data-quarto-table-cell-role="th">zone</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<th data-quarto-table-cell-role="th">doc_0</th>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>...</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">doc_1</th>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>...</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">doc_2</th>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>...</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr class="even">
<th data-quarto-table-cell-role="th">doc_3</th>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>...</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr class="odd">
<th data-quarto-table-cell-role="th">doc_4</th>
<td>0</td>
<td>0</td>