forked from interrogator/risk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
risk.py
1716 lines (1238 loc) · 70.1 KB
/
risk.py
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
# <markdowncell>
# Discourse-semantics of *risk* in the *New York Times*, 1963–2014
# ==========================================
# <markdowncell>
# **[Daniel McDonald](mailto:[email protected]?Subject=IPython%20NYT%20risk%20project), [Jens Zinn](mailto:[email protected]?Subject=IPython%20NYT%20risk%20project)**
#---------------------------
# <markdowncell>
# <br>
# > **SUMMARY:** This *IPython Notebook* demonstrates the findings from our investigation of *risk* in the NYT, as well as the code used to generate these findings. If you have the necessary dependencies installed, you can also use this notebook to interrogate and visualise the corpus yourself.
# <markdowncell>
# ### Setup
# <markdowncell>
# If you haven't already done so, the first things we need to do are **install corpkit**, download data for NLTK's tokeniser, and **unzip our corpus**.
# <codecell>
# install corpkit with either pip or easy_install
! easy_install -u corpkit
# <codecell>
# download nltk tokeniser data
import nltk
nltk.download('punkt')
nltk.download('wordnet')
# <codecell>
# unzip and untar our data
! gzip -dc data/nyt.tar.gz | tar -xf - -C data
# <markdowncell>
# Great! Now we have everything we need to start.
# <markdowncell>
# ### Orientation
# <markdowncell>
# Let's import the functions we'll be using to investigate the corpus. These functions are designed for this interrogation, but also have more general use in mind, so you can likely use them on your own corpora.
# | **Function name** | Purpose | |
# | ----------------- | ---------------------------------- | |
# | `interrogator()` | interrogate parsed corpora | |
# | `editor()` | edit `interrogator()` results | |
# | `plotter()` | visualise `interrogator()` results | |
# | `quickview()` | view `interrogator()` results | |
# | `multiquery()` | run a list of `interrogator()` queries | |
# | `conc()` | complex concordancing of subcorpora | |
# | `keywords()` | get keywords and ngrams from `conc()` output, subcorpora | |
# | `collocates()` | get collocates from `conc()` output, subcorpora| |
# | `quicktree()` | visually represent a parse tree | |
# | `searchtree()` | search a parse tree with a Tregex query | |
# | `save_result()` | save a result to disk | |
# | `load_result()` | load a saved result | |
# | `load_all_results()` | load every saved result into a dict | |
# <codecell>
import corpkit
import pandas as pd
from corpkit import (interrogator, editor, plotter, quickview, multiquery,
conc, keywords, colls, save_result, load_result)
# show figures in browser
% matplotlib inline
# <markdowncell>
# Next, let's set the path to our corpus. If you were using this interface for your own corpora, you would change this to the path to your data.
# <codecell>
# corpus of every article, with annual subcorpora
annual_trees = 'data/nyt/years'
# <markdowncell>
# Let's also quickly set some options for displaying raw data:
# <codecell>
pd.set_option('display.max_rows', 10)
pd.set_option('display.max_columns', 10)
pd.set_option('max_colwidth',70)
pd.set_option('display.width', 1000)
pd.set_option('expand_frame_repr', False)
# <markdowncell>
# ### Quickstart
# <markdowncell>
# Let's start off with some quick examples. By the end of this Notebook, you should be more than capable of reproducing even the most complex examples!
# <markdowncell>
# #### Interrogating the corpus (and saving the result)
# <codecell>
# <markdowncell>
# #### Editing results
# <markdowncell>
# ### The report
# <markdowncell>
# The focus of this notebook is our methodology and findings. These parts of the project are contextualised and elaborated upon in our written report of the project. Depending on your browser's capabilities/settings, the following will download or display our report:
# <codecell>
from corpkit import report_display
report_display()
# <markdowncell>
# ### The data
# <markdowncell>
# Our main corpus is comprised of paragraphs from *New York Times* articles that contain a risk word, which we have defined by Regular Expression as `'(?i)'.?\brisk.?\b'`. This includes *low-risk*, or *risk/reward* as single tokens, but excludes *brisk* or *asterisk*.
# The data comes from a number of sources.
# * 1963 editions were downloaded from ProQuest Newsstand as PDFs. Optical character recognition and manual processing was used to create a set of 1200 risk sentences.
# * The 1987–2006 editions were taken from the *NYT Annotated Corpus*.
# * 2007–2014 editions were downloaded from *ProQuest Newsstand* as HTML.
# In total, 149,504 documents were processed. The corpus from which the risk corpus was made is over 150 million words in length!
# The texts have been parsed for part of speech and grammatical structure by [`Stanford CoreNLP*](http://nlp.stanford.edu/software/corenlp.shtml). In this Notebook, we are only working with the parsed versions of the texts. We rely on [*Tregex*](http://nlp.stanford.edu/~manning/courses/ling289/Tregex.html) to interrogate the corpora. Tregex allows very complex searching of parsed trees, in combination with [Java Regular Expressions](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html). It's definitely worthwhile to learn the Tregex syntax, but in case you're time-poor, at the end of this notebook are a series of Tregex queries that you can copy and paste into `interrogator()` and `conc()` queries.
# <markdowncell>
# ### Interrogating the corpus
# <markdowncell>
# So, let's start by finding out how many words we have in each subcorpus. To do this, we'll interrogate the corpus using `interrogator()`. Its most important arguments are:
#
# 1. **path to corpus**
#
# 2. Tregex **options**:
#
# 3. a **Tregex query**
# | Option | Function |
# | :------|:-------|
# | `b` | get tag and word of Tregex match |
# | `c` | count Tregex match |
# | `d` | get dependent of regular expression match and the r/ship |
# | `f` | get dependency function of regular expression match |
# | `g` | get governor of regular expression match and the r/ship |
# | `i` | get dependency index of regular expression match |
# | `k` | Find keywords |
# | `n` | find n-grams |
# | `p` | get part-of-speech tag with Tregex |
# | `r` | regular expression, for plaintext corpora |
# | `s` | simple search string or list of strings for plaintext corpora |
# | `w` | get word(s)returned by Tregex/keywords/ngrams |
# We only need to count tokens, so we can use the `'count'` option (it's often faster than getting lists of matching tokens). The cell below will run `interrogator()` over each annual subcorpus and count the number of matches for the query.
# Some common Tregex patterns have been predefined. Searching for `'any'` will find any word in the corpus and count it.
# <codecell>
allwords = interrogator(annual_trees, 'count', 'any')
# <markdowncell>
# When the interrogation has finished, we can view our results:
# <codecell>
# from the allwords results, print the totals
print allwords.totals
# <markdowncell>
# If you want to see the query and options that created the results, you can use:
# <codecell>
print allwords.query
# <markdowncell>
# ### Plotting results
# <markdowncell>
# Lists of years and totals are pretty dry. Luckily, we can use the `plotter()` function to visualise our results. At minimum, `plotter()` needs two arguments:
# 1. a title (in quotation marks)
# 2. a list of results to plot
# <codecell>
plotter('Word counts in each subcorpus', allwords.totals)
# <markdowncell>
# Because we have smaller samples for 1963 and 2014, we might want to project them. To do that, we can pass subcorpus names and projection values to `editor()`:
# <codecell>
proj_vals = [(1963, 5), (2014, 1.37)]
projected = editor(allwords.totals, projection = proj_vals)
plotter('Word counts in each subcorpus (projected)', projected.totals)
# <markdowncell>
# Great! So, we can see that the number of words per year varies quite a lot, even after projection. That's worth keeping in mind.
# <markdowncell>
# ### Frequency of risk words in the NYT
# <markdowncell>
# Next, let's count the total number of risk words. Notice that we are using the `'both'` flag, instead of the `'count'` flag, because we want both the word and its tag.
# <codecell>
# our query:
riskwords_query = r'__ < /(?i).?\brisk.?\b/' # any risk word and its word class/part of speech
# get all risk words and their tags :
riskwords = interrogator(annual_trees, 'both', riskwords_query)
# <markdowncell>
# Even when do not use the `count` flag, we can access the total number of matches as before:
# <codecell>
riskwords.totals
# <markdowncell>
# At the moment, it's hard to tell whether or not these counts are simply because our annual NYT samples are different sizes. To account for this, we can calculate the percentage of parsed words that are risk words. This means combining the two interrogations we have already performed.
# We can do this by using `editor()`:
# <codecell>
# "plot riskwords.totals as a percentage of allwords.totals"
rel_riskwords = editor(riskwords.totals, '%', allwords.totals)
# <codecell>
plotter('Relative frequency of risk words', rel_riskwords.totals)
# <markdowncell>
# That's more helpful. We can now see some interesting peaks and troughs in the proportion of risk words. We can also see that 1963 contains the highest proportion of risk words. This is because the manual corrector of 1963 OCR entries preserved only the sentence containing risk words, rather than the paragraph.
# Here are two methods for excluding 1963 from the chart:
# <codecell>
# using Pandas syntax:
plotter('Relative frequency of risk words', rel_riskwords.totals.drop('1963'))
# the other way: using editor()
#rel_riskwords = editor(rel_riskwords.totals, skip_subcorpora = [1963])
#plotter('Relative frequency of risk words', rel_riskwords.totals)
# <markdowncell>
# Perhaps we're interested in not only the frequency of risk words, but the frequency of different *kinds* of risk words. We actually already collected this data during our last `interrogator()` query.
# We can print just the first few entries of the results list, rather than the totals list.
# <codecell>
# using Pandas syntax:
riskwords.results[range(10)]
# <codecell>
# using quickview
from corpkit import quickview
quickview(riskwords, 10)
# <markdowncell>
# So, let's use this data to do some more serious plotting:
# <codecell>
frac1 = editor(riskwords.results, '%', riskwords.totals)
# an alternative syntax:
# frac1 = editor(riskwords.results, '%', 'self')
# <codecell>
# a colormap is used for > 7 results
plotter('Risk word / all risk words', frac1.results, num_to_plot = 9)
# <markdowncell>
# If `plotter()` can't find a good spot for the legend, you can explicitly move it:
# <codecell>
plotter('Risk word / all risk words', frac1.results, num_to_plot = 9, legend_pos = 'lower right')
plotter('Risk word / all risk words', frac1.results, num_to_plot = 9, legend_pos = 'outside right')
# <codecell>
frac2 = editor(riskwords.results, '%', allwords.totals)
# <codecell>
plotter('Risk word / all words', frac2.results, legend_pos = 'outside right')
# <markdowncell>
# Another neat feature is the `.table` attribute of interrogations, which shows the most common `n` results in each subcorpus:
# <codecell>
riskwords.table
# <markdowncell>
# ### Customising visualisationsa
# <markdowncell>
# By default, `plotter()` plots the seven most frequent results, including 1963.
# We can use other `plotter()` arguments to customise what our chart shows. `plotter()`'s possible arguments are:
# | `plotter()` argument | Mandatory/default? | Use | Type |
# | :------|:------- |:-------------|:-----|
# | `title` | **mandatory** | A title for your plot | string |
# | `results` | **mandatory** | the results you want to plot | `interrogator()` or `editor()` output |
# | `num_to_plot` | 7 | Number of top entries to show | int |
# | `x_label` | False | custom label for the x-axis | str |
# | `y_label` | False | custom label for the y-axis | str |
# | `figsize` | (13, 6) | set the size of the figure | tuple: `(length, width)`|
# | `tex` | `'try'` | use *TeX* to generate image text | boolean |
# | `style` | `'ggplot'` | use Matplotlib styles | str: `'dark_background'`, `'bmh'`, `'grayscale'`, `'ggplot'`, `'fivethirtyeight'` |
# | `legend_pos` | `'default'` | legend position | str: `'outside right'` to move legend outside chart |
# | `show_totals` | `False` | Print totals on legend or plot where possible | str: '`legend`', '`plot`', '`both`', or 'False' |
# | `save` | `False` | Save to file | `True`: save as `title`.png. str: save as `str` |
# | `colours` | `'Paired'` | plot colours | str: any of Matpltlib's colormaps |
# | `cumulative` | `False` | plot entries cumulatively | bool |
# | `**kwargs` | False | pass other options to Pandas plot/Matplotlib | `rot = 45`, `subplots = True`, `fontsize = 16`, etc. |
# <codecell>
plotter('Risk words', frac2.results, num_to_plot = 5, y_label = 'Percentage of all words')
# <markdowncell>
# Keyword arguments for Pandas and matplotlib can also be used:
# <codecell>
plotter('Risk words', frac2.results.drop('1963'), subplots = True)
# <codecell>
# stacked bar chart
plotter('Risk words', frac2.results.drop('1963'), kind = 'bar', stacked = True, legend_pos = 'o r')
# <codecell>
# applying color scheme (see http://matplotlib.org/examples/color/colormaps_reference.html)
# not using tex for fonts
# setting a font size
plotter('Risk words', editor(frac2.results, just_entries= r'^\(v').results, kind = 'area',
stacked = True, legend_pos = 'o r', colours = 'Oranges', num_to_plot = 'all', fontsize = 16, tex = False)
# <markdowncell>
# Those already proficient with Python can use [Pandas' `plot()` function](http://pandas.pydata.org/pandas-docs/stable/visualization.html) if they like
# <markdowncell>
# Another neat thing you can do is save the results of an interrogation, so they don't have to be run the next time you load this notebook:
# <codecell>
# specify what to save, and a name for the file.
from corpkit import save_result, load_result
save_result(allwords, 'allwords')
# <markdowncell>
# You can then load these results:
# <codecell>
fromfile_allwords = load_result('allwords')
fromfile_allwords.totals
# <markdowncell>
# ... or erase them from memory:
# <codecell>
fromfile_allwords = None
# fromfile_allwords
# <markdowncell>
# ### `quickview()`
# <markdowncell>
# `quickview()` is a function that quickly shows the n most frequent items in a list. Its arguments are:
# 1. `interrogator()` or `editor()` output (preferably, the whole interrogation, not just the `.results` branch.)
# 2. number of results to show (default = 25)
# <codecell>
quickview(riskwords, n = 15)
# <markdowncell>
# The number shown next to the item is its index. You can use this number to refer to an entry when editing results.
# ### `editor()`
# <markdowncell>
# Results lists can be edited quickly with `editor()`. It has a lot of different options:
# | `editor()` argument | Mandatory/default? | Use | Type |
# | :------|:------- |:-------------|:-----|
# | `df` | **mandatory** | the results you want to edit | `interrogator()` or `editor` output |
# | `operation` | '%' | if using second list, what operation to perform | `'+', '-', '/', '*' or '%'` |
# | `df2` | False | Results to comine in some way with `df` | `interrogator()` or `editor` output (usually, a `.totals` branch) |
# | `just_subcorpora` | False | Subcorpora to keep | list |
# | `skip_subcorpora` | False | Subcorpora to skip | list |
# | `merge_subcorpora` | False | Subcorpora to merge | list |
# | `new_subcorpus_name` | False | name for merged subcorpora | index/str |
# | `just_entries` | False | Entries to keep | list |
# | `skip_entries` | False | Entries to skip | list |
# | `merge_entries` | False | Entries to merge | list of words or indices/a regex to match |
# | `sort_by` | False | sort results | str: `'total', 'infreq', 'name', 'increase', 'decrease'` |
# | `keep_top` | False | Keep only top n results after sorting | int |
# | `just_totals` | False | Collapse all subcorpora, return Series | bool |
# | `projection` | False | project smaller subcorpora | list of tuples: [`(subcorpus_name, projection_value)]` |
# | `**kwargs` | False | pass options to *Pandas*' `plot()` function, *Matplotlib* | various |
# <markdowncell>
# Let's try these out on a new interrogation. The query below will get adjectival risk words:
# <codecell>
adj = '/JJ.?/ < /(?i)\brisk/'
adj_riskwords = interrogator(annual_trees, 'words', adj)
# First, we can select specific subcorpora to keep, remove or span:
# <codecell>
editor(adj_riskwords.results, skip_subcorpora = [1963, 1987, 1988]).results
# <codecell>
editor(adj_riskwords.results, just_subcorpora = [1963, 1987, 1988]).results
# <codecell>
editor(adj_riskwords.results, span_subcorpora = [2000, 2010]).results
# <markdowncell>
# We can do similar kinds of things with each *result*:
# <codecell>
quickview(adj_riskwords.results)
# <codecell>
editor(adj_riskwords.results, skip_entries = [2, 5, 6]).results
# <codecell>
editor(adj_riskwords.results, just_entries = [2, 5, 6]).results
# <markdowncell>
# We can also use the words themselves, rather than indices, for all of these operations:
# <codecell>
editor(adj_riskwords.results, just_entries = ['risky', 'riskier', 'riskiest']).results
# <markdowncell>
# Or, we can use Regular Expressions:
# <codecell>
# skip any that start with 'r'
editor(adj_riskwords.results, skip_entries = r'^r').results
# <markdowncell>
# We can also merge entries, and specify a new name for the merged items. In lieu of a name, we can pass an index.
# <codecell>
editor(adj_riskwords.results, merge_entries = [2, 5, 6], newname = 'New name').results
# <codecell>
editor(adj_riskwords.results, merge_entries = ['risky', 'riskier', 'riskiest'], newname = 'risky').results
# <markdowncell>
# Notice how the merged result appears as the final column. To reorder the columns by total frequency, we can use `sort_by = 'total'`.
# <codecell>
# if we don't specify a new name, editor makes one for us
generated_name = editor(adj_riskwords.results, merge_entries = [2, 5, 6], sort_by = 'total')
quickview(generated_name.results)
# <markdowncell>
# `editor()` can sort also sort alphabetically, or by least frequent:
# <codecell>
# alphabetically
editor(adj_riskwords.results, sort_by = 'name').results
# <codecell>
# least frequent
editor(adj_riskwords.results, sort_by = 'infreq').results
# <markdowncell>
# Particularly cool is sorting by 'increase' or 'decrease': this calculates the trend lines of each result, and sort by the slope.
# <codecell>
editor(adj_riskwords.results, sort_by = 'increase').results
# <markdowncell>
# We can use `just_totals` to output just the sum of occurrences in each subcorpus:
# <codecell>
editor(adj_riskwords.results, just_totals = True).results
# <markdowncell>
# A handy thing about working with Pandas DataFrames is that we can easily translate our results to other formats:
# <codecell>
deceasing = editor(adj_riskwords.results, sort_by = 'decrease')
# <codecell>
# tranpose with T, get just top 5 results, print as CSV
print deceasing.results.T.head().to_csv()
# <codecell>
# or, print to latex markup:
print deceasing.results.T.head().to_latex()
# <markdowncell>
# Of course, you can perform many of these operations at the same time. Problems may arise, however, especially if your options contradict.
# <codecell>
editor(adj_riskwords.results, '%', adj_riskwords.totals, span_subcorpora = [1990, 2000],
just_entries = r'^\(n', merge_entries = r'(nns|nnp)', newname = 'Plural/proper', sort_by = 'name').results
# <markdowncell>
# ### Diversity of risk words
# <markdowncell>
# It's important to note that the kind of results we generate are hackable. We could count the number of unique risk words in each subcorpus by changing any count over 1 to 1.
# <codecell>
import numpy as np
# copy our list
uniques = adj_riskwords.results.copy()
# divide every result by itself
for f in uniques:
uniques[f] = uniques[f] / uniques[f]
# get rid of inf scores (i.e. 0 / 0) using numpy
uniques = uniques.replace(np.inf, 0)
# sum the results
u = uniques.T.sum()
# give our data a name
u.name = 'Unique risk words'
# <codecell>
plotter('Unique risk words', u.drop(['1963', '2014']), y_label = 'Number of unique risk words')
# <markdowncell>
# Just for fun, let's try that again with a few chart styles:
# <codecell>
for sty in ['dark_background', 'bmh', 'grayscale', 'fivethirtyeight', 'matplotlib']:
plotter('Unique risk words', u.drop(['1963', '2014']),
y_label = 'Number of unique risk words', style = sty)
# <markdowncell>
# So, we can see a generally upward trajectory, with more risk words constantly being used. Many of these results appear once, however, and many are nonwords. *Can you figure out how to remove words that appear only once per year?*
# <codecell>
#
# <markdowncell>
# ### conc()
# <markdowncell>
# `conc()` produces concordances of a subcorpus. Its main arguments are:
# 1. A subcorpus to search *(remember to put it in quotation marks!)*
# 2. A query
# If your data consists of parse trees, you can use a Tregex query. If your data is one or more plain-text files, you can just a regex. We'll show Tregex style here.
# <codecell>
lines = conc('data/nyt/years/1999', r'/JJ.?/ << /(?i).?\brisk.?\b/') # adj containing a risk word
# <markdowncell>
# You can set `conc()` to print only the first ten examples with `n = 10`, or ten random these with the `n = 15, random = True` parameter.
# <codecell>
lines = conc('data/nyt/years/2007', r'/VB.?/ < /(?i).?\brisk.?\b/', n = 15, random = True)
# <markdowncell>
# `conc()` takes another argument, window, which alters the amount of co-text appearing either side of the match. The default is 50 characters
# <codecell>
lines = conc('data/nyt/topics/health/2013', r'/VB.?/ << /(?i).?\brisk.?\b/', n = 15, random = True, window = 20)
# <markdowncell>
# `conc()` also allows you to view parse trees. By default, it's false:
# <codecell>
lines = conc('data/nyt/years/2013', r'/VB.?/ < /(?i)\btrad.?/', trees = True)
# <markdowncell>
# Just like our other data, conc lines can be edited with `editor()`, or outputted as CSV.
# <codecell>
lines = editor(lines, skip_entries = [1, 2, 4, 5])
print lines
# <markdowncell>
# If the concordance lines aren't print well, you can use `concprinter()`:
# <codecell>
from corpkit import concprinter
concprinter(lines)
# <markdowncell>
# Or, you can just use Pandas syntax:
# <codecell>
# Because there may be commas in the concordance lines,
# it's better to generate a tab-separated CSV:
print lines.to_csv(sep = '\t')
# <markdowncell>
# You can also print some `TeX`, if you're that way inclined:
# <codecell>
print lines.to_latex()
# <markdowncell>
# ### Keywords and ngrams
# <markdowncell>
# `corpkit` has some functions for keywording, ngramming and collocation. Each can take a number of kinds of input data:
# 1. a path to a subcorpus (of either parse trees or raw text)
# 2. `conc()` output
# 3. a string of text
# `keywords()` produces both keywords and ngrams. It relies on code from the [Spindle](http://openspires.oucs.ox.ac.uk/spindle/) project.
# <codecell>
from corpkit import keywords
keys, ngrams = keywords(lines)
for key in keys[:10]:
print key
for ngram in ngrams:
print ngram
# <markdowncell>
# You can also use `interrogator()` to search for keywords or ngrams. To do this, instead of a Tregex query, pass `'keywords'` or `'ngrams'`. You should also specify a dictionary to use as the reference corpus. If you specify `dictionary = 'self'`, a dictionary will be made of the entire corpus, saved, and used.
# <codecell>
kwds_bnc = interrogator(annual_trees, 'words', 'keywords', dictionary = 'bnc.p')
# <codecell>
kwds = interrogator(annual_trees, 'words', 'keywords', dictionary = 'self')
# <markdowncell>
# Now, rather than a frequency count, you will be given the keyness of each word.
# <codecell>
quickview(kwds.results)
# <codecell>
kwds.table
# <markdowncell>
# Let's sort these, based on those increasing/decreasing frequency:
# <codecell>
inc = editor(kwds.results, sort_by = 'increase')
dec = editor(kwds.results, sort_by = 'decrease')
# <markdowncell>
# ... and have a look:
# <codecell>
quickview(inc, 15)
# <codecell>
quickview(dec, 15)
# <markdowncell>
# As expected, really. Defunct states and former politicans are on the way out, while newer politicans are on the way in.
# <markdowncell>
# So, we can now do some pretty cool stuff in just a few lines of code. Let's concordance the top five keywords, looking at the year in which they are most key:
# <codecell>
import os
# iterate through results
for index, w in enumerate(list(kwds.results)[:5]):
# get the year with most occurrences
top_year = kwds.results[w].idxmax()
# print some info
print '\n%d: %s, %s' % (index + 1, w, str(top_year))
# get path to that subcorpus
top_dir = os.path.join(annual_trees, str(top_year))
# make a tregex query with token start and end defined
query = r'/(?i)^' + w + r'$/'
# do concordancing
lines = conc(top_dir, query, random = True, n = 10)
# <markdowncell>
# Neat, eh?
# Anyway, next, let's do a similar thing, but getting ngrams instead:
# <codecell>
ngms = interrogator(annual_trees, 'words', 'ngrams')
# <markdowncell>
# Neat. Now, let's make some thematic categories. This time, we'll make a list of tuples, containing regexes to match, and the result names:
# <codecell>
regexes = [(r'\b(legislature|medicaid|republican|democrat|federal|council)\b', 'Government organisations'),
(r'\b(empire|merck|commerical)\b', 'Companies'),
(r'\b(athlete|policyholder|patient|yorkers|worker|infant|woman|man|child|children|individual|person)\b', 'People, everyday'),
(r'\b(marrow|blood|lung|ovarian|breast|heart|hormone|testosterone|estrogen|pregnancy|prostate|cardiovascular)\b', 'The body'),
(r'\b(reagan|clinton|obama|koch|slaney|starzl)\b', 'Specific people'),
(r'\b(implant|ect|procedure|abortion|radiation|hormone|vaccine|medication)\b', 'Treatments'),
(r'\b(addiction|medication|drug|statin|vioxx)\b', 'Drugs'),
(r'\b(addiction|coronary|aneurysm|mutation|injury|fracture|cholesterol|obesity|cardiovascular|seizure|suicide)\b', 'Symptoms'),
(r'\b(worker|physician|doctor|midwife|dentist)\b', 'Healthcare professional'),
(r'\b(transmission|infected|hepatitis|virus|hiv|lung|aids|asbestos|malaria|rabies)\b', 'Infectious disease'),
(r'\b(huntington|lung|prostate|breast|heart|obesity)\b', 'Non-infectious disease'),
(r'\b(policyholder|reinsurance|applicant|capitation|insured|insurer|insurance|uninsured)\b', 'Finance'),
(r'\b(experiment|council|journal|research|university|researcher|clinical)\b', 'Research')]
# <markdowncell>
# Now, let's loop through out list and merge keyword and n-gram entries:
# <codecell>
# NOTE: you can use `print_info = False` if you don't want all this stuff printed.
for regex, name in regexes:
kwds = editor(kwds.results, merge_entries = regex, newname = name)
ngms = editor(ngms.results, merge_entries = regex, newname = name, print_info = False)
# now, remove all other entries
kwds = editor(kwds.results, just_entries = [name for regex, name in regexes])
ngms = editor(ngms.results, '%', ngms.totals, just_entries = [name for regex, name in regexes])
# <markdowncell>
# Pretty nifty, eh? Welp, let's plot them:
# <codecell>
plotter('Key themes: keywords', kwds.results.drop('1963'), y_label = 'L/L Keyness')
plotter('Key themes: n-grams', ngms.results.drop('1963'), y_label = 'Percentage of all n-grams')
# <markdowncell>
# ### Collocates
# <markdowncell>
# You can easily generate collocates for corpora, subcorpora or concordance lines:
# <codecell>
from corpkit import collocates
conc_colls = collocates(adj_lines)
for coll in conc_colls:
print coll
subc_colls = collocates('data/nyt/years/2003')
for coll in subc_colls:
if 'risk' not in coll:
print coll
# <markdowncell>
# With the `collocates()` function, you can specify the maximum distance at which two tokens will be considered collocates.
# <codecell>
colls = collocates(adj_lines, window = 3)
for coll in colls:
print coll
# <markdowncell>
# ### quicktree() and searchtree()
# <markdowncell>
# The two functions are useful for visualising and searching individual syntax trees. They have proven useful as a way to practice your Tregex queries.
# You could get trees by using `conc()` with a very large window and *trees* set to *True*. Alternatively, you can open files in the data directory directly, and paste them in.
# `quicktree()` generates a visual representation of a parse tree. Here's one from 1989:
# <codecell>
tree = '(ROOT (S (NP (NN Pre-conviction) (NN attachment)) (VP (VBZ carries) (PP (IN with) (NP (PRP it))) (NP (NP (DT the) (JJ obvious) (NN risk)) (PP (IN of) (S (VP (VBG imposing) (NP (JJ drastic) (NN punishment)) (PP (IN before) (NP (NN conviction)))))))) (. .)))'
# currently broken!
quicktree(tree)
# <markdowncell>
# `searchtree()` requires a tree and a Tregex query. It will return a list of query matches.
# <codecell>
print searchtree(tree, r'/VB.?/ >># (VP $ NP)')
print searchtree(tree, r'NP')
# <markdowncell>
# Now you're familiar with the corpus and functions. In the sections below, we'll perform a formal, followed by a functional, analysis of risk. Let's start with the formal side of things:
# <markdowncell>
# ### Word classes of risk words in the NYT
# <markdowncell>
# In formal grammar, as we saw earlier, risk words can be nouns, verbs, adjectives and adverbs. Though we've seen that there are a lot of nouns, and that nouns are becoming more frequent, we don't yet know whether or not nouns are becoming more frequent in the NYT generally. To test this, we can do as follows:
# <codecell>
# 'any' is a special query, which finds any tag if 'pos'
# and any word if 'words'.
baseline = interrogator(annual_trees, 'pos', 'any', lemmatise = True)
risk_pos = interrogator(annual_trees, 'pos', r'__ < /(?i).?\brisk.?/', lemmatise = True)
# <markdowncell>
# In the cell above, the `lemmatise = True` option will convert tags like `'NNS'` to `'Noun'`.
# <codecell>
quickview(baseline.results, n = 10)
# <codecell>
quickview(risk_pos.results)
# <markdowncell>
# Now, we can calculate the percentage of the time that a noun is a risk noun (and so on).
# <codecell>
open_words = ['Noun', 'Verb', 'Adjective', 'Adverb']
maths_done = editor(risk_pos.results, '%', baseline.results,
sort_by = 'total', just_entries = open_words, skip_subcorpora = [1963])
# <codecell>
plotter('Percentage of open word classes that are risk words',
maths_done.results, y_label = 'Percentage', legend_pos = 'lower left')
# <markdowncell>
# Neat, huh? We can see that nominalisation of risk is a very real thing.
# Our problem, however, is that formal categories like noun and verb only take us so far: in the phrase "risk metrics", risk is a noun, but performs a modifier function, for example. In the next section, we interrogate the corpus for *functional*, rather than *formal* categorisations of risk words.
# Before we start our corpus interrogation, we'll also present a *very* brief explanation of *Systemic Functional Linguistics*—the theory of language that underlies our analytical approach.
# <markdowncell>
# ### Functional linguistics
# <markdowncell>
# *Functional linguistics* is a research area concerned with how *realised language* (lexis and grammar) work to achieve meaningful social functions. One functional linguistic theory is *Systemic Functional Linguistics*, developed by Michael Halliday.
# <codecell>
from IPython.display import HTML
HTML('<iframe src=http://en.mobile.wikipedia.org/wiki/Michael_Halliday?useformat=mobile width=700 height=350></iframe>')
# <markdowncell>
# Central to the theory is a division between **experiential meanings** and **interpersonal meanings**.
# * Experiential meanings communicate what happened to whom, under what circumstances.
# * Interpersonal meanings negotiate identities and role relationships between speakers
# Halliday argues that these two kinds of meaning are realised **simultaneously** through different parts of English grammar.
# * Experiential meanings are made through **transitivity choices**.
# * Interpersonal meanings are made through **mood choices**
# Here's one visualisation of it. We're concerned with the two left-hand columns. Each level is an abstraction of the one below it.
# <br>
# <img style="float:left" src="https://raw.githubusercontent.com/interrogator/risk/master/images/egginsfixed.jpg" alt="SFL metafunctions" height="500" width="800" />
# <br>
# <markdowncell>
# Transitivity choices include fitting together configurations of:
# * Participants (*a man, green bikes*)
# * Processes (*sleep, has always been, is considering*)
# * Circumstances (*on the weekend*, *in Australia*)
# Mood features of a language include:
# * Mood types (*declarative, interrogative, imperative*)
# * Modality (*would, can, might*)
# * Lexical density—the number of words per clause, the number of content to non-content words, etc.
# Lexical density is usually a good indicator of the general tone of texts. The language of academia, for example, often has a huge number of nouns to verbs. We can approximate an academic tone simply by making nominally dense clauses:
# The consideration of interest is the potential for a participant of a certain demographic to be in Group A or Group B.
# Notice how not only are there many nouns (*consideration*, *interest*, *potential*, etc.), but that the verbs are very simple (*is*, *to be*).
# In comparison, informal speech is characterised by smaller clauses, and thus more verbs.
# A: Did you feel like dropping by?
# B: I thought I did, but now I don't think I want to
# Here, we have only a few, simple nouns (*you*, *I*), with more expressive verbs (*feel*, *dropping by*, *think*, *want*)
# > **Note**: SFL argues that through *grammatical metaphor*, one linguistic feature can stand in for another. *Would you please shut the door?* is an interrogative, but it functions as a command. *invitation* is a nominalisation of a process, *invite*. We don't have time to deal with these kinds of realisations, unfortunately.
# <markdowncell>
# ### Functional roles of *risk* in the NYT
# <markdowncell>
# > *A discourse analysis that is not based on grammar is not an analysis at all, but simply a running commentary on a text.* - [M.A.K. Halliday, 1994]()
#
# Our analysis proceeded according to the description of the transitivity system in *systemic functional grammar* ([SFG: see Halliday & Matthiessen, 2004](#ref:hallmat)).
# The main elements of the transitivity system are *participants* (the arguments of main verbs) and *processes* (the verbal group). Broadly speaking, processes can be modified by circumstances (adverbs and prepositional phrases, and participants can be modified through epithets, classifiers (determiners, adjectives, etc).
# > This is an oversimplification, of course. Grab a copy of the [*Introduction to Functional Grammar*](http://www.tandfebooks.com/isbn/9780203783771) to find out more.
# Risk words can potentially be participants, processes or modifiers.
# *Risk-as-participant*: any nominal argument of a process that is headed by a risk word. *Examples*:
#
# * *the big risk*
# * *considerable risk*
# * *the risk of cancer*
# * *risk-management*
# *Risk-as-process*: risk word as the rightmost component of a VP. **Examples**:
#
# * *he risked his life*
# * *the company could potentially risk it*
# *Risk-as-modifier*: any risk word that modifies a participant or process. This includes many adjectival risk words and many risk words appearing within prepositional or adverbial phrases. **Examples**:
#
# * *the chance of risk*
# * *risky business*
# * *they riskily arranged to meet*
# To find the distributions of these, we define three (very long and complicated) Tregex queries as sublists of titles and patterns under *query*. We then use `multiquery()` to search for each query in turn.
# <codecell>
query = (['Participant', r'/(?i).?\brisk.?/ > (/NN.?/ >># (NP !> PP !> (VP <<# (/VB.?/ < '
'/(?i)\b(take|takes|taking|took|taken|run|runs|running|ran|pose|poses|posed|posing)\b/)))) | >># (ADJP > VP)'],
['Process', r'VP !> VP << (/VB.?/ < /(?i).?\brisk.?/) | > VP <+(VP) (/VB.?/ < '
'/(?i)(take|taking|takes|taken|took|run|running|runs|ran|put|putting|puts|pose|poses|posed|posing)/'
'>># (VP < (NP <<# (/NN.?/ < /(?i).?\brisk.?/))))'],
['Modifier', r'/(?i).?\brisk.?/ !> (/NN.?/ >># (NP !> PP !> (VP <<# (/VB.?/ < '
'/(?i)\b(take|takes|taking|took|taken|run|runs|running|ran|pose|poses|posed|posing)\b/)))) & !>># '
'(ADJP > VP) & !> (/VB.?/ >># VP) & !> (/NN.?/ >># (NP > (VP <<# (/VB.?/ < /(?i)\b('
'take|takes|taking|took|taken|run|runs|running|ran|pose|poses|posed|posing)\b/))))'])
functional_role = multiquery(annual_trees, query)
# <codecell>
ppm = editor(functional_role.results, '%', allwords.totals)
# <codecell>
plotter('Risk as participant, process and modifier', ppm.results)
# <markdowncell>
# Here we can see that modifier forms are become more frequent over time, and have overtaken risk processes. Later, we determine which modifier forms in particular are becoming more common.
# <codecell>
# Perhaps you want to see the result without 1963?
plotter('Risk as participant, process and modifier', ppm.results.drop('1963'))
# <markdowncell>
# ### Risk as participant
# <markdowncell>
#
# > *You shall know a word by the company it keeps.* - [J.R. Firth, 1957](#ref:firth)
#
# Functionally, *risk* is most commonly a participant in the NYT. This gives us a lot of potential areas of interest. We'll go through a few here, but there are plenty of other things that we have to leave out for reasons of space.
# <markdowncell>
# ### Process types for participant risk
# <markdowncell>
# Here, we need to import verbose regular expressions that match any relational, verbal or mental process.
# <codecell>
from dictionaries.process_types import processes
print processes.relational
print processes.verbal
# <markdowncell>
# We can use these in our Tregex queries to look for the kinds of processes participant risks are involved in. First, let's get a count for all processes with risk participants:
# <codecell>
# get total number of processes with risk participant
query = r'/VB.?/ ># (VP ( < (NP <<# /(?i).?\brisk.?/) | >+(/.P$/) (VP $ (NP <<# /(?i).?\brisk.?/))))'
proc_w_risk_part = interrogator(annual_trees, 'count', query)
# <markdowncell>
# ### Relational processes with risk participant
# <codecell>
# subj_query = r'/VB.?/ < %s ># (VP >+(/.P$/) (VP $ (NP <<# /(?i).?\brisk.?/)))' % processes.relational
# obj_query = r'/VB.?/ < %s ># (VP < (NP <<# /(?i).?\brisk.?/))' % processes.relational
query = r'/VB.?/ < /%s/ ># (VP ( < (NP <<# /(?i).?\brisk.?/) | >+(/.P$/) (VP $ (NP <<# /(?i).?\brisk.?/))))' % processes.relational
relationals = interrogator(annual_trees, 'words', query, lemmatise = True)
# <codecell>
rels = editor(relationals.results, '%', proc_w_risk_part.totals)
# <codecell>
plotter('Relational processes', rels.results)
# <markdowncell>
# ### Adjectives modifying risk
# <markdowncell>
# First, we can look at adjectives that modify a participant risk.
# <codecell>
query = r'/JJ.?/ > (NP <<# /(?i).?\brisk.?/ ( > VP | $ VP))'
adj_modifiers = interrogator(annual_trees, 'words', query, lemmatise = True)
# <codecell>
adj = editor(adj_modifiers.results, '%', adj_modifiers.totals)
plotter('Adjectives modifying nominal risk (lemmatised)', adj.results, num_to_plot = 7)
# <markdowncell>
# Yuck! That doesn't tell us much. Let's try visualising the data in a few different ways. First, let's see what the top results look like...
# <codecell>
quickview(adj_modifiers.results)
# <markdowncell>
# OK, here are some ideas:
# <codecell>
# remove words with five or more letters
small_adjs = editor(adj_modifiers.results, '%', adj_modifiers.totals, skip_entries = r'.{5,}')
plotter('Adjectives modifying nominal risk (lemmatised)', small_adjs.results, num_to_plot = 6)
#get results with seven or more letters
big_adjs = editor(adj_modifiers.results, '%', adj_modifiers.totals, just_entries = '.{10,}')
plotter('Adjectives modifying nominal risk (lemmatised)', big_adjs.results, num_to_plot = 4)
#get a few interesting points
lst = ['more', 'high', 'calculated', 'potential']