-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnbtext.py
1681 lines (1416 loc) · 57.9 KB
/
nbtext.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
import json
import os
import random
from random import sample
import numpy as np
import numpy.random
import re
from collections import Counter
import inspect
import pandas as pd
import matplotlib.pyplot as plt
import requests
from IPython.display import HTML
import seaborn as sns
import networkx as nx
from pylab import rcParams
try:
from wordcloud import WordCloud
except ImportError:
print("wordcloud er ikke installert, kan ikke lage ordskyer")
#************** For defining wordbag search
def dict2pd(dictionary):
res = pd.DataFrame.from_dict(dictionary).fillna(0)
s = (res.mean(axis=0))
s = s.rename('snitt')
res = res.append(s)
return res.sort_values(by='snitt', axis=1, ascending=False).transpose()
def def2dict(ddef):
res = dict()
defs = ddef.split(';')
for d in defs:
lex = d.split(':')
if len(lex) == 2:
#print('#'.join(lex))
hyper = lex[0].strip()
occurrences = [x.strip() for x in lex[1].split(',')]
res[hyper] = occurrences
for x in res:
for y in res[x]:
if y.capitalize() not in res[x]:
res[x].append(y.capitalize())
return res
def wordbag_eval(wordbag, urns):
if type(urns) is list:
if isinstance(urns[0], list):
urns = [u[0] for u in urns]
else:
urns = urns
else:
urns = [urns]
param = dict()
param['wordbags'] = wordbag
param['urns'] = urns
r = requests.post("https://api.nb.no/ngram/wordbags", json = param)
return dict2pd(r.json())
def wordbag_eval_para(wordbag, urns):
if type(urns) is list:
if isinstance(urns[0], list):
urns = [u[0] for u in urns]
else:
urns = urns
else:
urns = [urns]
param = dict()
param['wordbags'] = wordbag
param['urns'] = urns
r = requests.post("https://api.nb.no/ngram/wordbags_para", json = param)
return r.json()
def get_paragraphs(urn, paras):
"""Return paragraphs for urn"""
param = dict()
param['paragraphs'] = paras
param['urn'] = urn
r = requests.get("https://api.nb.no/ngram/paragraphs", json=param)
return dict2pd(r.json())
### ******************* wordbag search end
def ner(text = None, dist=False):
"""Analyze text for named entities - set dist = True will return the four values that go into decision"""
r = []
if text != None:
r = requests.post("https://api.nb.no/ngram/ner", json={'text':text,'dist':dist})
return r.json()
#**** names ****
def check_navn(navn, limit=2, remove='Ja Nei Nå Dem De Deres Unnskyld Ikke Ah Hmm Javel Akkurat Jaja Jaha'.split()):
"""Removes all items in navn with frequency below limit and words in all case as well as all words in list 'remove'"""
r = {x:navn[x] for x in navn if navn[x] > limit and x.upper() != x and not x in remove}
return r
def sentences(urns, num=300):
if isinstance(urns[0], list):
urns = [str(x[0]) for x in urns]
params = {'urns':urns,
'num':num}
res = requests.get("https://api.nb.no/ngram/sentences", params=params)
return res.json()
def names(urn, ratio = 0.3, cutoff = 2):
""" Return namens in book with urn. Returns uni- , bi-, tri- and quadgrams """
if type(urn) is list:
urn = urn[0]
r = requests.get('https://api.nb.no/ngram/names', json={'urn':urn, 'ratio':ratio, 'cutoff':cutoff})
x = r.json()
result = (
Counter(x[0][0]),
Counter({tuple(x[1][i][0]):x[1][i][1] for i in range(len(x[1]))}),
Counter({tuple(x[2][i][0]):x[2][i][1] for i in range(len(x[2]))}),
Counter({tuple(x[3][i][0]):x[3][i][1] for i in range(len(x[3]))})
)
return result
def name_graph(name_struct):
m = []
for n in name_struct[0]:
m.append(frozenset([n]))
for n in name_struct[1:]:
m += [frozenset(x) for x in n]
G = []
for x in m:
for y in m:
if x < y:
G.append((' '.join(x), ' '.join(y)))
N = []
for x in m:
N.append(' '.join(x))
Gg = nx.Graph()
Gg.add_nodes_from(N)
Gg.add_edges_from(G)
return Gg
def aggregate_urns(urnlist):
"""Sum up word frequencies across urns"""
if isinstance(urnlist[0], list):
urnlist = [u[0] for u in urnlist]
r = requests.post("https://api.nb.no/ngram/book_aggregates", json={'urns':urnlist})
return r.json()
# Norweigan word bank
def word_variant(word, form):
""" Find alternative form for a given word form, e.g. word_variant('spiste', 'pres-part') """
r = requests.get("https://api.nb.no/ngram/variant_form", params={'word':word, 'form':form})
return r.json()
def word_paradigm(word):
""" Find alternative form for a given word form, e.g. word_variant('spiste', 'pres-part') """
r = requests.get("https://api.nb.no/ngram/paradigm", params = {'word': word})
return r.json()
def word_form(word):
""" Find alternative form for a given word form, e.g. word_variant('spiste', 'pres-part') """
r = requests.get("https://api.nb.no/ngram/word_form", params = {'word': word})
return r.json()
def word_lemma(word):
""" Find lemma form for a given word form """
r = requests.get("https://api.nb.no/ngram/word_lemma", params = {'word': word})
return r.json()
def word_freq(urn, words):
""" Find frequency of words within urn """
params = {'urn':urn, 'words':words}
r = requests.post("https://api.nb.no/ngram/freq", json=params)
return dict(r.json())
def tot_freq(words):
""" Find total frequency of words """
params = {'words':words}
r = requests.post("https://api.nb.no/ngram/word_frequencies", json=params)
return dict(r.json())
def book_count(urns):
params = {'urns':urns}
r = requests.post("https://api.nb.no/ngram/book_count", json=params)
return dict(r.json())
def sttr(urn, chunk=5000):
r = requests.get("https://api.nb.no/ngram/sttr", json = {'urn':urn, 'chunk':chunk})
return r.json()
def totals(top=200):
r = requests.get("https://api.nb.no/ngram/totals", json={'top':top})
return dict(r.json())
def navn(urn):
if type(urn) is list:
urn = urn[0]
r = requests.get('https://api.nb.no/ngram/tingnavn', json={'urn':urn})
return dict(r.json())
def digibokurn_from_text(T):
"""Return URNs as 13 digits (any sequence of 13 digits is counted as an URN)"""
return re.findall("(?<=digibok_)[0-9]{13}", T)
def urn_from_text(T):
"""Return URNs as 13 digits (any sequence of 13 digits is counted as an URN)"""
return re.findall("[0-9]{13}", T)
def metadata(urn=None):
urns = pure_urn(urn)
#print(urns)
r = requests.post("https://api.nb.no/ngram/meta", json={'urn':urns})
return r.json()
def pure_urn(data):
"""Convert URN-lists with extra data into list of serial numbers.
Args:
data: May be a list of URNs, a list of lists with URNs as their
initial element, or a string of raw texts containing URNs
Any pandas dataframe or series. Urns must be in the first column of dataframe.
Returns:
List[str]: A list of URNs. Empty list if input is on the wrong
format or contains no URNs
"""
korpus_def = []
if isinstance(data, list):
if not data: # Empty list
korpus_def = []
if isinstance(data[0], list): # List of lists
try:
korpus_def = [str(x[0]) for x in data]
except IndexError:
korpus_def = []
else: # Assume data is already a list of URNs
korpus_def = [str(int(x)) for x in data]
elif isinstance(data, str):
korpus_def = [str(x) for x in urn_from_text(data)]
elif isinstance(data, (int, np.integer)):
korpus_def = [str(data)]
elif isinstance(data, pd.DataFrame):
col = data.columns[0]
urns = pd.to_numeric(data[col])
korpus_def = [str(int(x)) for x in urns.dropna()]
elif isinstance(data, pd.Series):
korpus_def = [str(int(x)) for x in data.dropna()]
return korpus_def
#### N-Grams from fulltext updated
def unigram(word, period=(1950, 2020), media = 'bok', ddk=None, topic=None, gender=None, publisher=None, lang=None, trans=None):
r = requests.get("https://api.nb.no/ngram/unigrams", params={
'word':word,
'ddk':ddk,
'topic':topic,
'gender':gender,
'publisher':publisher,
'lang':lang,
'trans':trans,
'period0':period[0],
'period1':period[1],
'media':media
})
return frame(dict(r.json()))
def bigram(first,second, period=(1950, 2020), media = 'bok', ddk=None, topic=None, gender=None, publisher=None, lang=None, trans=None):
r = requests.get("https://api.nb.no/ngram/bigrams", params={
'first':first,
'second':second,
'ddk':ddk,
'topic':topic,
'gender':gender,
'publisher':publisher,
'lang':lang,
'trans':trans,
'period0':period[0],
'period1':period[1],
'media':media
})
return frame(dict(r.json()))
def book_counts(period=(1800, 2050)):
r = requests.get("https://api.nb.no/ngram/book_counts", params={
'period0':period[0],
'period1':period[1],
})
return frame(dict(r.json()))
####
def difference(first, second, rf, rs, years=(1980, 2000),smooth=1, corpus='bok'):
"""Compute difference of difference (first/second)/(rf/rs)"""
try:
a_first = nb_ngram(first, years=years, smooth=smooth, corpus=corpus)
a_second = nb_ngram(second, years=years, smooth=smooth, corpus=corpus)
a = a_first.join(a_second)
b_first = nb_ngram(rf, years=years, smooth=smooth, corpus=corpus)
b_second = nb_ngram(rs, years=years, smooth=smooth, corpus=corpus)
if rf == rs:
b_second.columns = [rs + '2']
b = b_first.join(b_second)
s_a = a.mean()
s_b = b.mean()
f1 = s_a[a.columns[0]]/s_a[a.columns[1]]
f2 = s_b[b.columns[0]]/s_b[b.columns[1]]
res = f1/f2
except:
res = 'Mangler noen data - har bare for: ' + ', '.join([x for x in a.columns.append(b.columns)])
return res
def df_combine(array_df):
"""Combine one columns dataframes"""
import pandas as pd
cols = []
for i in range(len(a)):
#print(i)
if array_df[i].columns[0] in cols:
array_df[i].columns = [array_df[i].columns[0] + '_' + str(i)]
cols.append(array_df[i].columns[0])
return pd.concat(a, axis=1, sort=True)
def col_agg(df, col='sum'):
c = df.sum(axis=0)
c = pd.DataFrame(c)
c.columns = [col]
return c
def row_agg(df, col='sum'):
c = df.sum(axis=1)
c = pd.DataFrame(c)
c.columns = [col]
return c
def get_freq(urn, top=50, cutoff=3):
"""Get frequency list for urn"""
if isinstance(urn, list):
urn = urn[0]
r = requests.get("https://api.nb.no/ngram/urnfreq", json={'urn':urn, 'top':top, 'cutoff':cutoff})
return Counter(dict(r.json()))
####=============== GET URNS ==================##########
def book_corpus(words = None, author = None,
title = None, subtitle = None, ddk = None, subject = None,
period=(1100, 2020),
gender=None,
lang = None,
trans= None,
limit=20 ):
return frame(book_urn(words, author, title, subtitle, ddk, subject, period, gender, lang, trans, limit),
"urn author title year".split())
def book_urn(words = None, author = None,
title = None, subtitle = None, ddk = None, subject = None,
period=(1100, 2020),
gender=None,
lang = None,
trans= None,
limit=20 ):
"""Get URNs for books with metadata"""
frame = inspect.currentframe()
args, _, _, values = inspect.getargvalues(frame)
query = {i:values[i] for i in args if values[i] != None and i != 'period'}
query['year'] = period[0]
query['next'] = period[1] - period[0]
return get_urn(query)
def unique_urns(korpus, newest=True):
author_title = {(c[1],c[2]) for c in korpus}
corpus = {(c[0], c[1]):[d for d in korpus if c[0] == d[1] and c[1]==d[2]] for c in author_title }
for c in corpus:
corpus[c].sort(key=lambda c: c[3])
if newest == True:
res = [corpus[c][-1] for c in corpus]
else:
res = [corpus[c][0] for c in corpus]
return res
def refine_book_urn(urns = None, words = None, author = None,
title = None, ddk = None, subject = None, period=(1100, 2020), gender=None, lang = None, trans= None, limit=20 ):
"""Refine URNs for books with metadata"""
# if empty urns nothing to refine
if urns is None or urns == []:
return []
# check if urns is a metadata list, and pick out first elements if that is the case
if isinstance(urns[0], list):
urns = [x[0] for x in urns]
frame = inspect.currentframe()
args, _, _, values = inspect.getargvalues(frame)
query = {i:values[i] for i in args if values[i] != None and i != 'period' and i != 'urns'}
query['year'] = period[0]
query['next'] = period[1] - period[0]
#print(query)
return refine_urn(urns, query)
def best_book_urn(word = None, author = None,
title = None, ddk = None, subject = None, period=(1100, 2020), gender=None, lang = None, trans= None, limit=20 ):
"""Get URNs for books with metadata"""
if word is None:
return []
frame = inspect.currentframe()
args, _, _, values = inspect.getargvalues(frame)
query = {i:values[i] for i in args if values[i] != None and i != 'period' and i != 'word'}
query['year'] = period[0]
query['next'] = period[1] - period[0]
return get_best_urn(word, query)
def get_urn(metadata=None):
"""Get urns from metadata"""
if metadata is None:
metadata = {}
if not ('next' in metadata or 'neste' in metadata):
metadata['next'] = 100
if not 'year' in metadata:
metadata['year'] = 1900
r = requests.get('https://api.nb.no/ngram/urn', json=metadata)
return r.json()
def refine_urn(urns, metadata=None):
"""Refine a list urns using extra information"""
if metadata is None:
metadata = {}
metadata['urns'] = urns
if not ('words' in metadata):
metadata['words'] = []
if not ('next' in metadata or 'neste' in metadata):
metadata['next'] = 520
if not 'year' in metadata:
metadata['year'] = 1500
r = requests.post('https://api.nb.no/ngram/refineurn', json=metadata)
return r.json()
def get_best_urn(word, metadata=None):
"""Get the best urns from metadata containing a specific word"""
metadata['word'] = word
if not ('next' in metadata or 'neste' in metadata):
metadata['next'] = 600
if not 'year' in metadata:
metadata['year'] = 1500
r = requests.get('https://api.nb.no/ngram/best_urn', json=metadata)
return r.json()
def get_papers(top=5, cutoff=5, navn='%', yearfrom=1800, yearto=2020, samplesize=100):
"""Get newspapers"""
div = lambda x, y: (int(x/y), x % y)
chunks = 20
# split samplesize into chunks, go through the chunks and then the remainder
(first, second) = div(samplesize, chunks)
r = []
# collect chunkwise
for i in range(first):
r += requests.get("https://api.nb.no/ngram/avisfreq", json={'navn':navn, 'top':top, 'cutoff':cutoff,
'yearfrom':yearfrom, 'yearto':yearto,'samplesize':chunks}
).json()
# collect the remainder
r += requests.get("https://api.nb.no/ngram/avisfreq", json={'navn':navn, 'top':top, 'cutoff':cutoff,
'yearfrom':yearfrom, 'yearto':yearto,'samplesize':second}
).json()
return [dict(x) for x in r]
def urn_coll(word, urns=[], after=5, before=5, limit=1000):
"""Find collocations for word in a set of book URNs. Only books at the moment"""
if isinstance(urns[0], list): # urns assumed to be list of list with urn-serial as first element
urns = [u[0] for u in urns]
r = requests.post("https://api.nb.no/ngram/urncoll", json={'word':word, 'urns':urns,
'after':after, 'before':before, 'limit':limit})
res = pd.DataFrame.from_dict(r.json(), orient='index')
if not res.empty:
res = res.sort_values(by=res.columns[0], ascending = False)
return res
def urn_coll_words(words, urns=None, after=5, before=5, limit=1000):
"""Find collocations for a group of words within a set of books given by a list of URNs. Only books at the moment"""
coll = pd.DataFrame()
if urns != None:
if isinstance(urns[0], list): # urns assumed to be list of list with urn-serial as first element
urns = [u[0] for u in urns]
colls = Counter()
if isinstance(words, str):
words = words.split()
res = Counter()
for word in words:
try:
res += Counter(
requests.post(
"https://api.nb.no/ngram/urncoll",
json={
'word':word,
'urns':urns,
'after':after,
'before':before,
'limit':limit}
).json()
)
except:
True
coll = pd.DataFrame.from_dict(res, orient='index')
if not coll.empty:
coll = coll.sort_values(by=coll.columns[0], ascending = False)
return coll
def get_aggregated_corpus(urns, top=0, cutoff=0):
res = Counter()
if isinstance(urns[0], list): # urns assumed to be list of list with urn-serial as first element
urns = [u[0] for u in urns]
for u in urns:
#print(u)
res += get_freq(u, top = top, cutoff = cutoff)
return pd.DataFrame.from_dict(res, orient='index').sort_values(by=0, ascending = False)
def compare_word_bags(bag_of_words, another_bag_of_words, first_freq = 0, another_freq = 1, top=100, first_col = 0, another_col= 0):
"""Compare two columns taken from two or one frame. Parameters x_freq are frequency limits used to cut down candidate words
from the bag of words. Compare along the columns where first_col and another_col are column numbers. Typical situation is that
bag_of_words is a one column frame and another_bag_of_words is another one column frame. When the columns are all from one frame,
just change column numbers to match the columns"""
diff = bag_of_words[bag_of_words > first_freq][bag_of_words.columns[first_col]]/another_bag_of_words[another_bag_of_words > another_freq][another_bag_of_words.columns[another_col]]
return frame(diff, 'diff').sort_values(by='diff', ascending=False)[:top]
def collocation(
word,
yearfrom=2010,
yearto=2018,
before=3,
after=3,
limit=1000,
corpus='avis',
lang='nob',
title='%',
ddk='%',
subtitle='%'):
"""Defined collects frequencies for a given word"""
data = requests.get(
"https://api.nb.no/ngram/collocation",
params={
'word':word,
'corpus':corpus,
'yearfrom':yearfrom,
'before':before,
'after':after,
'limit':limit,
'yearto':yearto,
'title':title,
'ddk':ddk,
'subtitle':subtitle}).json()
return pd.DataFrame.from_dict(data['freq'], orient='index')
def collocation_data(words, yearfrom = 2000, yearto = 2005, limit = 1000, before = 5, after = 5, title = '%', corpus='bok'):
"""Collocation for a set of words sum up all the collocations words is a list of words or a blank separated string of words"""
import sys
a = dict()
if isinstance(words, str):
words = words.split()
for word in words:
print(word)
try:
a[word] = collocation(
word,
yearfrom = yearfrom, yearto = yearto, limit = limit,
corpus = corpus, before = before,
after = after, title = title
)
a[word].columns = [word]
except:
print(word, ' feilsituasjon', sys.exc_info())
result = pd.DataFrame()
for w in a:
result = result.join(a[w], how='outer')
return pd.DataFrame(result.sum(axis=1)).sort_values(by=0, ascending=False)
class CollocationCorpus:
from random import sample
def __init__(self, corpus = None, name='', maximum_texts = 500):
urns = pure_urn(corpus)
if len(urns) > maximum_texts:
selection = random(urns, maximum_texts)
else:
selection = urns
self.corpus_def = selection
self.corpus = get_aggregated_corpus(self.corpus_def, top=0, cutoff=0)
def summary(self, head=10):
info = {
'corpus_definition':self.corpus[:head],
'number_of_words':len(self.corpus)
}
return info
def collocation_old(word, yearfrom=2010, yearto=2018, before=3, after=3, limit=1000, corpus='avis'):
data = requests.get(
"https://api.nb.no/ngram/collocation",
params={
'word':word,
'corpus':corpus,
'yearfrom':yearfrom,
'before':before,
'after':after,
'limit':limit,
'yearto':yearto}).json()
return pd.DataFrame.from_dict(data['freq'], orient='index')
def heatmap(df, color='green'):
return df.fillna(0).style.background_gradient(cmap=sns.light_palette(color, as_cmap=True))
def get_corpus_text(urns, top = 0, cutoff=0):
k = dict()
if isinstance(urns, list):
# a list of urns, or a korpus with urns as first element
if isinstance(urns[0], list):
urns = [u[0] for u in urns]
else:
# assume it is a single urn, text or number
urns = [urns]
for u in urns:
#print(u)
k[u] = get_freq(u, top = top, cutoff = cutoff)
df = pd.DataFrame(k)
res = df.sort_values(by=df.columns[0], ascending=False)
return res
def normalize_corpus_dataframe(df):
colsums = df.sum()
for x in colsums.index:
#print(x)
df[x] = df[x].fillna(0)/colsums[x]
return True
def show_korpus(korpus, start=0, size=4, vstart=0, vsize=20, sortby = ''):
"""Show corpus as a panda dataframe
start = 0 indicates which dokument to show first, dataframe is sorted according to this
size = 4 how many documents (or columns) are shown
top = 20 how many words (or rows) are shown"""
if sortby != '':
val = sortby
else:
val = korpus.columns[start]
return korpus[korpus.columns[start:start+size]].sort_values(by=val, ascending=False)[vstart:vstart + vsize]
def aggregate(korpus):
"""Make an aggregated sum of all documents across the corpus, here we use average"""
return pd.DataFrame(korpus.fillna(0).mean(axis=1))
def convert_list_of_freqs_to_dataframe(referanse):
"""The function get_papers() returns a list of frequencies - convert it"""
res = []
for x in referanse:
res.append( dict(x))
result = pd.DataFrame(res).transpose()
normalize_corpus_dataframe(result)
return result
def get_corpus(top=0, cutoff=0, navn='%', corpus='avis', yearfrom=1800, yearto=2020, samplesize=10):
if corpus == 'avis':
result = get_papers(top=top, cutoff=cutoff, navn=navn, yearfrom=yearfrom, yearto=yearto, samplesize=samplesize)
res = convert_list_of_freqs_to_dataframe(result)
else:
urns = get_urn({'author':navn, 'year':yearfrom, 'neste':yearto-yearfrom, 'limit':samplesize})
res = get_corpus_text([x[0] for x in urns], top=top, cutoff=cutoff)
return res
class Cluster:
def __init__(self, word = '', filename = '', period = (1950,1960) , before = 5, after = 5, corpus='avis', reference = 200,
word_samples=1000):
if word != '':
self.collocates = collocation(word, yearfrom=period[0], yearto = period[1], before=before, after=after,
corpus=corpus, limit=word_samples)
self.collocates.columns = [word]
if type(reference) is pd.core.frame.DataFrame:
reference = reference
elif type(reference) is int:
reference = get_corpus(yearfrom=period[0], yearto=period[1], corpus=corpus, samplesize=reference)
else:
reference = get_corpus(yearfrom=period[0], yearto=period[1], corpus=corpus, samplesize=int(reference))
self.reference = aggregate(reference)
self.reference.columns = ['reference_corpus']
self.word = word
self.period = period
self.corpus = corpus
else:
if filename != '':
self.load(filename)
def cluster_set(self, exponent=1.1, top = 200, aslist=True):
combo_corp = self.reference.join(self.collocates, how='outer')
normalize_corpus_dataframe(combo_corp)
korpus = compute_assoc(combo_corp, self.word, exponent)
korpus.columns = [self.word]
if top <= 0:
res = korpus.sort_values(by=self.word, ascending=False)
else:
res = korpus.sort_values(by=self.word, ascending=False).iloc[:top]
if aslist == True:
res = HTML(', '.join(list(res.index)))
return res
def add_reference(self, number=20):
ref = get_corpus(yearfrom=self.period[0], yearto=self.period[1], samplesize=number)
ref = aggregate(ref)
ref.columns = ['add_ref']
normalize_corpus_dataframe(ref)
self.reference = aggregate(self.reference.join(ref, how='outer'))
return True
def save(self, filename=''):
if filename == '':
filename = "{w}_{p}-{q}.json".format(w=self.word,p=self.period[0], q = self.period[1])
model = {
'word':self.word,
'period':self.period,
'reference':self.reference.to_dict(),
'collocates':self.collocates.to_dict(),
'corpus':self.corpus
}
with open(filename, 'w', encoding = 'utf-8') as outfile:
print('lagrer til:', filename)
outfile.write(json.dumps(model))
return True
def load(self, filename):
with open(filename, 'r') as infile:
try:
model = json.loads(infile.read())
#print(model['word'])
self.word = model['word']
self.period = model['period']
self.corpus = model['corpus']
self.reference = pd.DataFrame(model['reference'])
self.collocates = pd.DataFrame(model['collocates'])
except:
print('noe gikk galt')
return True
def search_words(self, words, exponent=1.1):
if type(words) is str:
words = [w.strip() for w in words.split()]
df = self.cluster_set(exponent=exponent, top=0, aslist=False)
sub= [w for w in words if w in df.index]
res = df.transpose()[sub].transpose().sort_values(by=df.columns[0], ascending=False)
return res
def wildcardsearch(params=None):
if params is None:
params = {'word': '', 'freq_lim': 50, 'limit': 50, 'factor': 2}
res = requests.get('https://api.nb.no/ngram/wildcards', params=params)
if res.status_code == 200:
result = res.json()
else:
result = {'status':'feil'}
resultat = pd.DataFrame.from_dict(result, orient='index')
if not(resultat.empty):
resultat.columns = [params['word']]
return resultat
def sorted_wildcardsearch(params):
res = wildcardsearch(params)
if not res.empty:
res = res.sort_values(by=params['word'], ascending=False)
return res
def make_newspaper_network(key, wordbag, titel='%', yearfrom='1980', yearto='1990', limit=500):
if type(wordbag) is str:
wordbag = wordbag.split()
r = requests.post("https://api.nb.no/ngram/avisgraph", json={
'key':key,
'words':wordbag,
'yearto':yearto,
'yearfrom':yearfrom,
'limit':limit})
G = nx.Graph()
if r.status_code == 200:
G.add_weighted_edges_from([(x,y,z) for (x,y,z) in r.json() if z > 0 and x != y])
else:
print(r.text)
return G
def make_network(urn, wordbag, cutoff=0):
if type(urn) is list:
urn = urn[0]
if type(wordbag) is str:
wordbag = wordbag.split()
G = make_network_graph(urn, wordbag, cutoff)
return G
def make_network_graph(urn, wordbag, cutoff=0):
r = requests.post("https://api.nb.no/ngram/graph", json={'urn':urn, 'words':wordbag})
G = nx.Graph()
G.add_weighted_edges_from([(x,y,z) for (x,y,z) in r.json() if z > cutoff and x != y])
return G
def make_network_name_graph(urn, tokens, tokenmap=None, cutoff=2):
if isinstance(urn, list):
urn = urn[0]
# tokens should be a list of list of tokens. If it is list of dicts pull out the keys (= tokens)
if isinstance(tokens[0], dict):
tokens = [list(x.keys()) for x in tokens]
r = requests.post("https://api.nb.no/ngram/word_graph", json={'urn':urn, 'tokens':tokens, 'tokenmap':tokenmap})
#print(r.text)
G = nx.Graph()
G.add_weighted_edges_from([(x,y,z) for (x,y,z) in r.json() if z > cutoff and x != y])
return G
def token_convert_back(tokens, sep='_'):
""" convert a list of tokens to string representation"""
res = [tokens[0]]
for y in tokens:
res.append([tuple(x.split(sep)) for x in y])
l = len(res)
for x in range(1, 4-l):
res.append([])
return res
def token_convert(tokens, sep='_'):
""" convert back to tuples """
tokens = [list(x.keys()) for x in tokens]
tokens = [[(x,) for x in tokens[0]], tokens[1], tokens[2], tokens[3]]
conversion = []
for x in tokens:
conversion.append([sep.join(t) for t in x])
return conversion
def token_map_to_tuples(tokens_as_strings, sep='_', arrow='==>'):
tuples = []
for x in tokens_as_strings:
token = x.split(arrow)[0].strip()
mapsto = x.split(arrow)[1].strip()
tuples.append((tuple(token.split(sep)), tuple(mapsto.split(sep))))
#tuples = [(tuple(x.split(arrow).strip()[0].split(sep)), tuple(x.split(arrow)[1].strip().split(sep))) for x in tokens_as_strings]
return tuples
def token_map(tokens, strings=False, sep='_', arrow= '==>'):
""" tokens as from nb.names()"""
if isinstance(tokens[0], dict):
# get the keys(), otherwise it is already just a list of tokens up to length 4
tokens = [list(x.keys()) for x in tokens]
# convert tokens to tuples and put them all in one list
tokens = [(x,) for x in tokens[0]] + tokens[1] + tokens[2] + tokens[3]
tm = []
#print(tokens)
for token in tokens:
if isinstance(token, str):
trep = (token,)
elif isinstance(token, list):
trep = tuple(token)
token = tuple(token)
else:
trep = token
n = len(trep)
#print(trep)
if trep[-1].endswith('s'):
cp = list(trep[:n-1])
cp.append(trep[-1][:-1])
cp = tuple(cp)
#print('copy', cp, trep)
if cp in tokens:
#print(trep, cp)
trep = cp
larger = [ts for ts in tokens if set(ts) >= set(trep)]
#print(trep, ' => ', larger)
larger.sort(key=lambda x: len(x), reverse=True)
tm.append((token,larger[0]))
res = tm
if strings == True:
res = [sep.join(x[0]) + ' ' + arrow + ' ' + sep.join(x[1]) for x in tm]
return res
def draw_graph_centrality(G, h=15, v=10, fontsize=20, k=0.2, arrows=False, font_color='black', threshold=0.01):
node_dict = nx.degree_centrality(G)
subnodes = dict({x:node_dict[x] for x in node_dict if node_dict[x] >= threshold})
x, y = rcParams['figure.figsize']
rcParams['figure.figsize'] = h, v
pos =nx.spring_layout(G, k=k)
ax = plt.subplot()
ax.set_xticks([])
ax.set_yticks([])
G = G.subgraph(subnodes)
nx.draw_networkx_labels(G, pos, font_size=fontsize, font_color=font_color)
nx.draw_networkx_nodes(G, pos, alpha=0.5, nodelist=subnodes.keys(), node_size=[v * 1000 for v in subnodes.values()])
nx.draw_networkx_edges(G, pos, alpha=0.7, arrows=arrows, edge_color='lightblue', width=1)
rcParams['figure.figsize'] = x, y
return True
def combine(clusters):
"""Make new collocation analyses from data in clusters"""
colls = []
collocates = clusters[0].collocates
for c in clusters[1:]:
collocates = collocates.join(c.collocates, rsuffix='-' + str(c.period[0]))
return collocates
def cluster_join(cluster):
clusters = [cluster[i] for i in cluster]
clst = clusters[0].cluster_set(aslist=False)
for c in clusters[1:]:
clst = clst.join(c.cluster_set(aslist=False), rsuffix = '_'+str(c.period[0]))
return clst
def serie_cluster(word, startår, sluttår, inkrement, before=5, after=5, reference=150, word_samples=500):
tidscluster = dict()
for i in range(startår, sluttår, inkrement):
tidscluster[i] = Cluster(
word,
corpus='avis',
period=(i, i + inkrement - 1),
before=after,
after=after,
reference=reference,
word_samples=word_samples)
print(i, i+inkrement - 1)
return tidscluster
def save_serie_cluster(tidscluster):
for i in tidscluster:
tidscluster[i].save()
return 'OK'
def les_serie_cluster(word, startår, sluttår, inkrement):
tcluster = dict()
for i in range(startår, sluttår, inkrement):
print(i, i+inkrement - 1)
tcluster[i] = Cluster(filename='{w}_{f}-{t}.json'.format(w=word, f=i,t=i+inkrement - 1))
return tcluster
def make_cloud(json_text, top=100, background='white', stretch=lambda x: 2**(10*x), width=500, height=500, font_path=None):
pairs0 = Counter(json_text).most_common(top)
pairs = {x[0]:stretch(x[1]) for x in pairs0}
wc = WordCloud(
font_path=font_path,
background_color=background,
width=width,
#color_func=my_colorfunc,
ranks_only=True,
height=height).generate_from_frequencies(pairs)
return wc
def draw_cloud(sky, width=20, height=20, fil=''):
plt.figure(figsize=(width,height))