-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpmizer2.py
1514 lines (1182 loc) · 54.3 KB
/
pmizer2.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
#from dictionary import dct
import itertools
import json
import math
import re
import statistics
import sys
import time
from urllib.parse import quote
import random
from collections import Counter
__version__ = "2024-05-19"
print('pmizer.py version %s\n' % __version__)
""" Constants """
WINDOW_SCALING = False # Apply window size penalty to scores
LOGBASE = 2 # Logarithm base; set to None for ln
LACUNAE = ['_'] # List of symbols for lacunae or removed words
LINEBREAK = '<LB>' # Line break or text boundary
BUFFER = '<BF>' # Buffer/padding symbol
INDENT = 4 # Indentation level for print
METASEPARATOR = '|' # Character for separating multi-dimensional
# metadata for JSON
WRAPCHARS = ['[', ']'] # Wrap translations/POS-tags between these
# symbols, e.g. ['"'] for "string". Give two
# if beginning and end symbols are different
DECIMALSEPARATOR = '.' # Decimal separator for output files
HIDE_MIN_SCORE = True # Hide minimum scores in matrices
VERBOSE = True # Print more info
IGNORE = [LINEBREAK, BUFFER]
""" /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
Aleksi Sahala 2019-2024
github.com/asahala
Critical bug fixes:
2019-06-26: changed buffering from the end of the line
to the beginning to prevent rare crash that
occurred if the keyword was coincidentally
in the middle of the first symmetric window.
now linebreak is always the first symbol in text.
2020-02-10: lazy context similarity algorithm now preserves
lacuna positions. other algorithms are not
recommended as they are not fixed yet.
2020-03-03: regular expressions now work properly in forward-
looking windows.
symmetric window scaling is now correct and
Σ f(a,b) = Σ f(a) = Σ f(b) = N when I(σ+;σ+)
where σ is symbol of the alphabet.
2020-05-20: Fix incorrect bounds for PMI3. Lazy context
similarity measure now discards collocates
from counts properly (i.e. subtracts 1 from
the denominator).
2024-05-19: Fix links to Korp.
Other fixes:
2020-11-27: Preweight is now default.
2020-01-01: Additional measures such as Jaccard etc.
How to use? =====================================================
(1) Create text object (text per line, lemmas separated by space)
text = Text('oracc-akkadian.txt')
(2) Calculate co-occurrencies for the text object
cooc = Associations(text,
words1=['*'], # All words to all words
formulaic_measure=Lazy, # Use CSW
minfreq_b = 1, # Min freq of b
minfreq_ab = 1, # Min co-oc freq of a and b
symmetry=True, # Window symmetry
windowsize=5, # Window size
factorpower=2) # k-value
(3) Calculate PMI from co-occurrences from the associations object
results = cooc.score(PMI2) # Select association measure
(4) Print results from
x.print_scores(results, limit=1000, gephi=True, filename='oracc.pmi')
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ """
""" ====================================================================
Logarithm base definiton; log-base 2 should be used by default =========
==================================================================== """
def _log(n):
if LOGBASE is None:
return math.log(n)
else:
return math.log(n, LOGBASE)
def make_korp_oracc_url(w1, w2, wz):
""" Generate URL for Oracc in Korp """
w1 = re.sub('(.+)_.+?', r'\1', w1)
w2 = re.sub('(.+)_.+?', r'\1', w2)
w1 = w1.split('[')[0]
w2 = w2.split('[')[0]
base = 'https://www.kielipankki.fi/korp/?mode=other_languages#'\
'?lang=en&stats_reduce=word'
cqp = '&cqp=%5Blemma%20%3D%20%22{w1}%22%5D%20%5B%5D%7B0,'\
'{wz}%7D%20%5Blemma%20%3D%20%22{w2}%22%5D'\
.format(w1=quote(w1), w2=quote(w2), wz=wz)
corps = '&corpus=oracc_adsd,oracc_ario,oracc_blms,oracc_cams,oracc_caspo,oracc_ctij'\
',oracc_dcclt,oracc_dccmt,oracc_ecut,oracc_etcsri,oracc_hbtin,oracc_obmc,'\
'oracc_riao,oracc_ribo,oracc_rimanum,oracc_rinap,oracc_saao,'\
'oracc_others&search_tab=1&search=cqp&within=paragraph'
## TEMPORARY FOR ALP COURSE, REMOVE THE LINE BELOW
corps = '&corpus=oracc2021_rinap&search_tab=1&search=cqp&within=paragraph'
return base+cqp+corps
""" ====================================================================
Input / Output tools ===================================================
==================================================================== """
class IO:
""" Basic file IO-operations and verbose """
def read_file(filename):
print(': Reading %s' % filename)
try:
with open(filename, 'r', encoding='utf-8', errors='ignore') as data:
return data.read().splitlines()
except FileNotFoundError:
IO.errormsg("File not found: %s" % filename)
sys.exit(0)
def write_file(filename, content):
with open(filename, 'w', encoding='utf-8') as data:
data.write(content)
print(': Saved %s' % filename)
def export_json(filename, content):
""" Save lookup table as JSON """
with open(filename, 'w', encoding="utf-8") as data:
json.dump(content, data)
print(': Saved %s' % filename)
def import_json(filename):
""" Load lookup table from JSON """
try:
print(': Reading %s' % filename)
with open(filename, encoding='utf-8') as data:
return json.load(data)
except FileNotFoundError:
IO.errormsg("File not found: %s" % filename)
sys.exit(0)
def show_time(time_, process):
if VERBOSE:
print("%s%s took %0.2f seconds" \
% (" "*INDENT, process, round(time_, 2)))
def printmsg(message):
if VERBOSE:
print(message)
@staticmethod
def errormsg(message):
print(": Error! %s" % message)
""" ====================================================================
Word association measures ==============================================
Measures take four arguments:
ab = co-oc freq
a = freq of a
b = freq of b
cz = corpus size
factor = CSW value (this is used if postweight is set)
oo = estimated number of all bigrams in the corpus
==================================================================== """
class FREQ:
minimum = 0
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
return ab
## POINTWISE MUTUAL INFORMATION BASED MEASURES
class PMI:
""" Pointwise Mutual Information. The score orientation is
-log p(a,b) > 0 > -inf. As in Church & Hanks 1990. """
minimum = -math.inf
@staticmethod
def raw(ab, a, b, cz, oo=None):
return (ab/cz) / ((a/cz)*(b/cz))
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
return factor * (_log(ab*cz) - _log(a*b))
class PMIDELTA:
""" Smooth PMI (Pantel & Lin 2002). This measure reduces
the PMI score more, the rarer the words are, thus reducing
the low-frequency bias """
minimum = -math.inf
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
weight = (ab/(ab+1)) * (min(a,b)/(min(a,b,)+1))
return factor * weight * (_log(ab*cz) - _log(a*b))
class PMICDS:
""" Context distribution smoothed PMI (Levy, Goldberg &
Dagan 2015). This measure raises the f(b) to the power of
alpha = 0.75 """
minimum = -math.inf
## WORKS ONLY IN MATRIX FACTORIZATION
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
alpha = 0.75
return max(factor * _log((cz*ab) / (a*(b**alpha))),0)
class NPMI:
""" Normalized PMI. The score orientation is +1 > 0 > -1
as in Bouma 2009 """
minimum = -1.0
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
return factor * (PMI.score(ab, a, b, cz, 1) / -_log(ab/cz))
class PMISIG:
""" Washtell & Markert (2009). """
minimum = -math.inf
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
pa = a / cz
pb = b / cz
return factor * (math.sqrt(min(pa, pb))\
* (PMI.raw(ab, a, b, cz)))
class SCISIG:
""" Washtell & Markert (2009) The original publication does
not tell the score orientation, but it can be shown to be
+1 > √p(a,b) > 0 """
minimum = 0
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
pa = a / cz
pb = b / cz
pab = ab / cz
return factor * (math.sqrt(min(pa, pb))\
* (pab / ((pa) * math.sqrt(pb))))
class cPMI:
""" Corpus Level Significant PMI as in Damani 2013. According to
the original research paper, delta value of 0.9 is recommended """
minimum = -math.inf
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
delta = 0.9
t = math.sqrt(_log(delta) / (-2 * a))
return _log(ab / (a * b / cz) + a * t) * factor
class PMI2:
""" PMI^2. Fixes the low-frequency bias of PMI and NPMI by squaring
the numerator to compensate multiplication done in the denominnator.
Scores are oriented as: 0 > log p(a,b) > -inf. As in Daille 1994 """
minimum = -math.inf
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
return (PMI.score(ab, a, b, cz, 1) - (-_log(ab/cz))) / factor
class PMI3:
""" PMI^3 (no low-freq bias, favors common bigrams). Although not
mentioned in any papers at my disposal, the scores are oriented
log p(a,b) > 2 log p(a,b) > -inf. As in Daille 1994"""
minimum = -math.inf
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
return (PMI.score(ab, a, b, cz, 1) - (-(2*_log(ab/cz)))) / factor
class SPMI:
""" Positive shifted PMI. Works as the regular PMI but discards negative
scores: -log p(a,b) > 0 = 0; Shift by 3 """
minimum = 0
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
return max(3 + PMI.score(ab, a, b, cz, factor), 0)
class PPMI:
""" Positive PMI. Works as the regular PMI but discards negative
scores: -log p(a,b) > 0 = 0 """
minimum = 0
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
return max(PMI.score(ab, a, b, cz, factor), 0)
class PPMI2:
""" Positive derivative of PMI^2 as in Role & Nadif 2011.
Shares exaclty the same properties but the score orientation
is on the positive plane: 1 > 2^log p(a,b) > 0 """
minimum = 0
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
return factor * (2 ** PMI2.score(ab, a, b, cz, 1))
class PPMI3:
""" Positive derivative of PMI^3. Shares exaclty the same properties
but the score orientation is: p(a,b) > p(a,b)^2 > 0
Not mentioned in Role & Nadif """
minimum = 0
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
return factor * (2 ** PMI3.score(ab, a, b, cz, 1))
class NPMI2:
""" NPMI^2. Removes the low-frequency bias as PMI^2 and has
a fixed score orientation as NPMI: 1 > 0 = 0. Take cube root
of the result to trim excess decimals. Sahala & Linden (2020) """
minimum = 0
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
ind = 2 ** _log(ab / cz)
base_score = 2 ** PMI2.score(ab, a, b, cz, 1) - ind
return (max(base_score / (1 - ind), 0) * factor) ** (1/3)
class NPMI3:
""" NPMI^3. Removes the low-frequency bias as PMI^3 and has
a fixed score orientation as NPMI: 1 > 0 = 0. Take cube root
of the result to trim excess decimals. Sahala & Linden (2020) """
minimum = 0
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
pab = (ab/cz)
base_score = 2 ** PMI3.score(ab, a, b, cz, 1) - (pab**2)
return (max(base_score / (pab - (pab**2)), 0) * factor) ** (1/3)
# Other measures and statistical tests
class NormalizedExpectation:
""" Normalized Expectation as in Pecina 2006
2f(xy) / f(x)f(y) """
minimum = 0
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
return (2*ab*factor) / (a+b)
class tTest:
""" Student's t-test """
minimum = 0
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
ind = a*b/cz
return ((ab*factor)-ind) / math.sqrt(factor*ab*(1-(factor*ab/cz)))
class zScore:
""" Z-score """
minimum = 0
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
ind = a*b/cz
return ((ab*factor)-ind) / math.sqrt(ind*(1-(ind/cz)))
# Association coefficients, See Pecina 2006
def c_table(ab, a, b, cz, factor, oo=None):
""" Return contingency table. Note that the total number of
co-occurrences in the corpus is based on an estimate, because
not all bigrams are calculated for efficiency """
ab = ab*factor
A = ab
B = a - ab
C = b - ab
D = oo - ab
return A, B, C, D
class Jaccard:
minimum = 0
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
A, B, C, D = c_table(ab, a, b, cz, factor, oo)
return A / (A+B+C)
class Odds:
minimum = 0
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
A, B, C, D = c_table(ab, a, b, cz, factor, oo)
return (A*D)/(B*C)
class Simpson:
""" Note: this has an extreme low-freq bias """
minimum = 0
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
A, B, C, D = c_table(ab, a, b, cz, factor, oo)
return A / min(A+B, A+C)
class BraunBlanquet:
minimum = 0
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
A, B, C, D = c_table(ab, a, b, cz, factor, oo)
return A / max(A+B, A+C)
class Pearson:
minimum = 0
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
A, B, C, D = c_table(ab, a, b, cz, factor, oo)
u = (A * D) - (B * C)
d = math.sqrt((A+B)*(A+C)*(D+B)*(D+C))
return u / d
class UnigramSubtuples:
minimum = 0
@staticmethod
def score(ab, a, b, cz, factor, oo=None):
A, B, C, D = c_table(ab, a, b, cz, factor, oo)
subs = [1/A, 1/B, 1/C, 1/D]
return _log((A*D)/(B*C)) - (3.29 * math.sqrt(sum(subs)))
""" ====================================================================
Context Similarity Weighting ===========================================
========================================================================
An initial version of CSW as in Sahala & Linden 2020. Performs similarly
but has a space complexity of O(n×m^2) (n = corpus size, m = window len)
==================================================================== """
class FormulaicMeasures:
@staticmethod
def compensate(words, collocate, uniqs):
""" Compensate window matrix counts:
´compensation´ is a number of each word that should be
ignored in counting (metasymbols, collocates) """
compensation = uniqs
for symbol in LACUNAE + [BUFFER, LINEBREAK, collocate]:
compensation += max(words.count(symbol) - 1, 0)
return compensation
class Greedy:
""" Removed temporarily """
pass
class Lazy:
@staticmethod
def score(windows, collocate):
diffs = []
for window in zip(*windows[::-1]):
""" Count the number of unique words in transposed window matrix
ie. stack windows and count uniques, see compensate() for more
info """
uniqs = len(set(window))
compensated = FormulaicMeasures.compensate(window, collocate, uniqs)
diffs.append((len(window) - compensated) / len(window))
""" Uncomment to see probabilities """
#print('\t'.join(window), (len(window) - compensated) / len(window))
return sum(diffs) / max((len(diffs) - 1),1)
""" ====================================================================
Text container and basic text analysis tools ===========================
==================================================================== """
class Text(object):
def __init__(self, filename, ignore=LACUNAE):
self.filename = filename
self.content = []
self.content_uniq = []
self.metadata = []
self.documents = []
self.translations = {}
self.ignore = ignore
self._read(filename)
def __repr__(self):
return self.stats
@staticmethod
def _tokenize(string):
return string.strip().split(' ')
@staticmethod
def _count(symbols, line):
return len([s for s in line if s in symbols])
def _read(self, filename):
st = time.time()
""" Read input text from lemmatized raw text file """
metalength = None
self.lacunacount = 0
self.maxlen = 0
self.linecount = 0
self.corpus_size = 0
for line in IO.read_file(self.filename):
if line:
self.linecount += 1
fields = line.split('\t')
text = fields[-1]
if metalength is None:
metalength = [len(fields)]
elif len(fields) not in metalength:
IO.errormsg('(%s at line %i): Inconsistent '\
'number of metadata fields.' % (self.filename,
self.linecount))
sys.exit(0)
if len(fields) > 1:
""" Collect metadata """
meta = METASEPARATOR.join(fields[0:-1])
self.metadata.append(meta)
lemmas = self._tokenize(text)
""" Store documents for TF-IDF """
self.documents.append(lemmas)
self.lacunacount += self._count(self.ignore, lemmas)
""" Lacunae are count as lemmas but buffers are not """
lemmacount = len(lemmas)
self.corpus_size += lemmacount
if lemmacount > self.maxlen:
self.maxlen = lemmacount
self.content.extend([LINEBREAK] + [BUFFER] + lemmas)
""" Add buffer to the end of the file """
self.content.extend([BUFFER])
""" Make frequency list """
self.word_freqs = Counter(self.content)
st2 = time.time() - st
IO.show_time(st2, "Reading")
IO.printmsg(self.stats)
@property
def stats(self):
""" Return corpus statistics """
tab = INDENT * ' '
non_words = [BUFFER, LINEBREAK]
freqs = sorted([f for f in self.word_freqs.values()])
log = [('\n: Text statistics:'),
('%sLines: %i' % (tab, self.linecount)),
('%sLongest line: %i' % (tab, self.maxlen)),
('%sWord count: %i' % (tab, self.corpus_size)),
('%sWord count (non-lacunae): %i' \
% (tab, self.corpus_size - self.lacunacount)),
('%sLacunae or ignored symbols: %i' % (tab, self.lacunacount)),
('%sUnique words: %i' \
% (tab, len(self.word_freqs.keys()) - len(non_words))),
('%sMedian word frequency: %i' \
% (tab, statistics.median(freqs))),
('%sAverage word frequency: %.2f' \
% (tab, sum(freqs) / len(freqs)))]
return '\n'.join(log) + '\n'
@property
def metadata_stats(self):
""" Return word and line counts for each metadata group """
if not self.metadata:
return None
meta = {}
tab = ' '*INDENT
for index, content in enumerate(self.documents):
wordcount = len(content)
meta.setdefault(self.metadata[index], {'words': 0, 'lines': 0})
meta[self.metadata[index]]['words'] += wordcount
meta[self.metadata[index]]['lines'] += 1
return '\n'+'\n'.join([('%s%s\t%i\t%i' \
% (tab, k.replace(METASEPARATOR, '\t'), v['words'], v['lines']))\
for k, v in sorted(meta.items())]) + '\n'
def iterate(self, windowsize=1):
""" Iterate content of the text and extend buffers to match
window size """
for word in self.content:
if word == BUFFER:
for i in range(0, windowsize):
yield word
else:
yield word
def tf_idf(self, threshold=0):
""" Returns a TF-IDF based stopword list based on the text.
This can be passed to Associations() as a keyword argument
´threshold´ defines the size of the list, if no argument is
give, will return a list relative to corpus size """
print(': Making TF-IDF stopword list')
st = time.time()
tf_idfs = {}
words = []
if threshold == 0:
threshold = int(0.000005 * self.corpus_size)
for document in self.documents:
N = len(document)
for word in set(document):
t = document.count(word)
tf_idfs.setdefault(word, {'tf': [], 'found_in': 0})
tf_idfs[word]['tf'].append(t/N)
tf_idfs[word]['found_in'] += 1
for word, vals in tf_idfs.items():
scores = []
for tf in vals['tf']:
scores.append(tf * math.log(len(self.documents)/vals['found_in'], 10))
words.append([sum(scores), word])
st2 = time.time() - st
IO.show_time(st2, "TF-IDF")
return [x[1] for x in sorted(words, reverse=True)[0:threshold]]
def read_dict(self):
filename = self.filename.split('.')[0] + '.dict'
with open(filename, 'r', encoding='utf-8', errors='ignore') as data:
for line in data.read().splitlines():
key, value = line.split('\t')
self.translations[key] = value
def uniquify(self, wz):
# This feature is not finished
""" Produce a version of text that do not need window scaling.
Iterate text and disallow words occurring more than once
withing a given distance from each other. Replace non-unique
words with lacunae """
print(': Uniquifying windows')
st = time.time()
count = 0
count_non_lacunae = 0
removed = 0
for word in self.content:
""" Initialize buffer """
if word == LINEBREAK:
buffer = []
""" Keep buffer length """
if len(buffer) == wz + 1:
buffer.pop(0)
""" Replace non-uniques with lacunae """
if word in buffer and word not in LACUNAE + IGNORE:
removed += 1
word = LACUNAE[0]
if word not in IGNORE:
count += 1
if word not in LACUNAE:
count_non_lacunae += 1
buffer.append(word)
self.content_uniq.append(word)
self.corpus_size_uniq = Counter(self.content_uniq)
st2 = time.time() - st
IO.show_time(st2, "Uniquifying")
print("%s--> %i words removed" \
% (' '*INDENT, removed))
#for k, v in sorted(Counter(removed).items()):
# print(v, k)
""" ================================================================
Random sampling tools (for measure evaluation purposes)
================================================================ """
""" Sample a population of words from frequency list from
given frequency range. ´quantity´ is the population size and
´freq_range´ a list that contains the min and max freq,
e.g. [30,50] """
def pick_random(self, quantity, freq_range):
sampled = []
for k, v in self.word_freqs.items():
if freq_range[1] > v > freq_range[0]:
sampled.append(k)
self.random_sample = random.sample(sampled, quantity)
return self.random_sample
""" Random samples can be saved and loaded with the
following funtions """
def save_random(self, filename):
with open(filename, 'w', encoding='utf-8') as data:
data.write('\n'.join(self.random_sample))
def load_random(self, filename):
with open(filename, 'r', encoding='utf-8') as data:
self.random_sample = data.read().splitlines()
return self.random_sample
""" ====================================================================
Association measure tools ==============================================
==================================================================== """
class Associations:
def __init__(self, text, **kwargs):
if not isinstance(text, Text):
IO.errormsg('Association must have Text object as argument.')
sys.exit(0)
self.text = text
self.word_freqs = self.text.word_freqs
self.corpus_size = self.text.corpus_size
self.windowsize = 2
self.minfreq_b = 1
self.minfreq_ab = 1
self.distances = {}
self.WINS = {}
self.translations = {}
if self.text.translations:
self.translations = self.text.translations
self.track_distance = False
self.symmetry = False
self.track_distance = False
self.positive_condition = False
self.formulaic_measure = None
self.postweight = False
self.factorpower = 1
self.words = {1: [], 2: []}
self.regex_words = {1: [], 2: []}
self.metadata = {}
self.conditions = {'stopwords': LACUNAE + ['', BUFFER, LINEBREAK],
'stopwords_regex': [],
'conditions': [],
'conditions_regex': []}
self.set_constraints(**kwargs)
self.count_bigrams()
if self.corpus_size < self.windowsize:
IO.errormsg('Window size exceeds corpus size.')
sys.exit(1)
def __repr__(self):
""" Define what is not shown in .log files """
debug = []
tab = max([len(k)+2 for k in self.__dict__.keys()])
for k in sorted(self.__dict__.keys()):
if k not in ['scored', 'text', 'regex_stopwords', 'metadata',
'regex_words', 'distances', 'anywords',
'anywords1', 'output', 'anywords2', 'bigram_freqs',
'anycondition', 'word_freqs', 'positive_condition',
'minimum', 'WINS', 'documents', 'translations']:
v = self.__dict__[k]
debug.append('%s%s%s' % (k, ' '*(tab-len(k)+1), str(v)))
return '\n'.join(debug) + '\n' + '-'*20 +\
' \npmizer version: ' + __version__
def set_constraints(self, **kwargs):
""" Set constraints. Separate regular expressions from the
string variables, as string comparison is significantly faster
than re.match() """
for key, value in kwargs.items():
if key in ['stopwords', 'conditions']:
for word in value:
if isinstance(word, str):
self.conditions[key].append(word)
else:
self.conditions[key+'_regex'].append(word)
elif key in ['words1', 'words2']:
index = int(key[-1])
for word in value:
if isinstance(word, str):
self.words[index].append(word)
else:
self.regex_words[index].append(word)
else:
setattr(self, key, value)
""" Combine tables for faster comparison """
self.anywords = any([self.words[1], self.words[2],
self.regex_words[1], self.regex_words[2]])
self.anywords1 = any([self.words[1], self.regex_words[1]])
self.anywords2 = any([self.words[2], self.regex_words[2]])
self.anycondition = any([self.conditions['conditions'],
self.conditions['conditions_regex']])
""" ================================================================
Helper funtions ====================================================
================================================================ """
def _trim_float(self, number):
if not number:
return number
elif isinstance(number, int):
return number
else:
return round(number, 3)
def _get_translation(self, word):
""" Get translation from dictionary """
try:
translation = '%s%s%s' % (WRAPCHARS[0], self.translations[word], WRAPCHARS[-1])
except:
translation = '%s?%s' % (WRAPCHARS[0], WRAPCHARS[-1])
return translation
def _get_distance(self, bigram):
""" Calculate average distance for bigram's words; if not
used, the distance will be equal to window size. """
if self.track_distance:
distance = self._trim_float(sum(self.distances[bigram])
/ len(self.distances[bigram]))
else:
distance = ''
return distance
def _match_regex(self, words, regexes):
""" Matches a list of regexes to list of words """
return any([re.match(r, w) for r in regexes for w in words])
def _meets_anycondition(self, condition, words):
""" Compare words with stopword/conditions list and regexes. """
if not self.conditions[condition +'_regex']:
return any(w in self.conditions[condition] for w in words)
else:
return self._match_regex(words, self.conditions[condition+'_regex'])\
or any(w in self.conditions[condition] for w in words)
def _is_wordofinterest(self, word, index):
""" Compare words with the list of words of interest.
Return True if in the list; never accept lacunae or buffers """
if self.words[1] == ['*'] and word not in [LINEBREAK, BUFFER]:
return True
if word in [LINEBREAK, BUFFER]:
return False
if not self.regex_words[index]:
return word in self.words[index]
else:
return self._match_regex([word], self.regex_words[index])\
or word in self.words[index]
def _is_valid(self, w1, w2, freq):
""" Validate bigram. Discard stopwords and those which
do not match with the word of interest lists """
if freq >= self.minfreq_ab and self.word_freqs[w2] >= self.minfreq_b:
if not self.anywords:
return not self._meets_anycondition('stopwords', [w1, w2])
elif self.anywords and self.anywords2:
return self._is_wordofinterest(w1, 1) and\
self._is_wordofinterest(w2, 2)
else:
if self.anywords1:
return self._is_wordofinterest(w1, 1) and\
not self._meets_anycondition('stopwords', [w2])
if self.anywords2:
return self._is_wordofinterest(w2, 2) and\
not self._meets_anycondition('stopwords', [w1])
else:
return False
else:
return False
def _has_condition(self, window):
""" Check if conditions are defined. Validate window if true """
if not self.anycondition:
return True
else:
if self.positive_condition:
if self._meets_anycondition('conditions', window):
return True
else:
return False
elif not self.positive_condition:
if not self._meets_anycondition('conditions', window):
return True
else:
return False
else:
print('positive_condition must be True or False')
sys.exit(1)
""" ================================================================
Bigram counting ====================================================
================================================================ """
def count_bigrams(self):
print(': Counting bigrams')
st = time.time()
""" Set has_meta if metadata is available. """
has_meta = len(self.text.metadata) > 0