-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbinit.py
752 lines (640 loc) · 29.5 KB
/
dbinit.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
from controllers.sql import SQLController
from controllers.ui import debug, error
from utils.grammar import case_list, plurality_list, person_list, tense, mood, \
long_syllable, separate_syllables, Gender, gender_list
from settings import old_english_word_json, modern_english_word_json
from utils.web import use_unverified_ssl
import json
from settings import data_path
from typing import List, Tuple, Dict, Union
import os.path as path
from tqdm import tqdm
import re
etymology_names = ['inh', 'der']
language_codes = ['ang', 'en']
def db_string(s: str) -> str:
return '"{}"'.format(s.replace('"', "'"))
def convert_word_dictionary_noun(words: List[Dict[str, Union[List[str],
Dict[str, str],
str]]]) -> Dict[str, List[tuple]]:
"""
:param words: List of dictionaries to be converted
{
'word': word,
'definitions': List of definitions,
'forms': List of dictionaries with case entries
}
:return: Returns a dictionary with each key corresponding to a table and it's value a list of data to insert
"""
debug('Converting Noun dictionaries')
roots = []
declensions = []
for w in tqdm(words):
for d in w['definitions']:
roots.append((db_string(w['word']), '"noun"', db_string(d),
w['word'].startswith('-') or w['word'].endswith('-'))) # Check for affix
for decl in w['forms']:
for c, d in decl.items():
case, plurality = c.split(' ')
declensions.append((db_string(d), w['word'],
db_string(plurality.lower()), db_string(case.lower())))
return {'old_english_words': roots, 'declensions': declensions}
def convert_word_dictionary_verb(words: List[Tuple[str, Dict[str, Union[List[str],
List[Dict[str,
Union[str, Dict[str, str]]]],
str]]]]) -> Dict[str, List[tuple]]:
"""
:param words: List of dictionaries to be converted
{
'word': word,
'definitions': List of definitions,
'forms': A List of conjugation dictionaries
Conjugation dictionaries: {
'key': The name indicating the conjugation form of this entry
'form' The form of the root verb for this conjugation
}
}
Possible keys for conjugation dictionaries:
('infinitive can', 0, 1),
('infinitive to', 0, 2),
('indicative first singular present', 2, 1),
('indicative first singular past', 2, 2),
('indicative second singular present', 3, 1),
('indicative second singular past', 3, 2),
('indicative third singular present', 4, 1),
('indicative third singular past', 4, 2),
('indicative plural present', 5, 1),
('indicative plural past', 5, 2),
('subjunctive singular present', 7, 1),
('subjunctive singular past', 7, 2),
('subjunctive plural present', 8, 1),
('subjunctive plural past', 8, 2),
('imperative singular', 9, 1),
('imperative plural', 10, 1),
('present participle', 12, 1),
('past participle', 12, 2)
:return: Returns a dictionary with each key corresponding to a table and it's value a list of data to insert
"""
debug('Converting Verb dictionaries')
roots = []
conjugations = []
verbs = []
for s, w in tqdm(words):
for d in w['definitions']:
roots.append((db_string(w['word']), '"verb"', db_string(d),
w['word'].startswith('-') or w['word'].endswith('-'))) # Check for affix
verbs.append((w['word'], False, 0, s == 'transitive'))
for conj in w['forms']:
for c, d in conj.items():
origin = w['word']
word = db_string(d)
person = '"none"'
plurality = '"none"'
emood = '"none"'
etense = '"none"'
is_participle = False
is_infinitive = False
tags = c.split(' ')
if len(tags) == 2:
if tags[0] == 'imperative':
emood = db_string(tags[0].lower())
plurality = db_string(tags[1].lower())
elif tags[0] == 'infinitive':
is_infinitive = True
is_participle = tags[1] == 'can'
else:
is_participle = True
etense = db_string(tags[0].lower())
elif len(tags) == 3:
emood = db_string(tags[0].lower())
plurality = db_string(tags[1].lower())
etense = db_string(tags[2].lower())
elif len(tags) == 4:
emood = db_string(tags[0].lower())
person = db_string(tags[1].lower())
plurality = db_string(tags[2].lower())
etense = db_string(tags[3].lower())
else:
debug('{} is not a valid tag name for a verb'.format(c))
conjugations.append((word, origin, person, plurality, emood, etense, is_participle, is_infinitive))
return {'old_english_words': roots, 'conjugations': conjugations, 'verbs': verbs}
def convert_word_dictionary_adverb(words: List[Tuple[str, Dict[str, Union[List[str],
List[Dict[str,
Union[str, Dict[str, str]]]],
str]]]]) -> Dict[str, List[tuple]]:
"""
:param words: List of dictionaries to be converted
{
'word': word,
'definitions': List of definitions,
'forms': A List of conjugation dictionaries
}
:return: Returns a dictionary with each key corresponding to a table and it's value a list of data to insert
"""
debug('Converting Adverb dictionaries')
roots = []
adverbs = {}
for s, w in tqdm(words):
for d in w['definitions']:
roots.append((db_string(w['word']), '"adverb"', db_string(d),
w['word'].startswith('-') or w['word'].endswith('-'))) # Check for affix
if w['word'] not in adverbs:
adverbs[w['word']] = {'comparative': False, 'superlative': False}
if s == 'comparative':
adverbs[w['word']]['comparative'] = True
elif s == 'superlative':
adverbs[w['word']]['superlative'] = True
adverb_entries = []
for w in adverbs.keys():
adverb_entries.append((w, adverbs[w]['comparative'], adverbs[w]['superlative']))
return {'old_english_words': roots, 'adverbs': adverb_entries}
def convert_word_dictionary_adjectives(words: List[Dict[str, Union[List[str], List[Dict[str,
Union[str, Dict[str, str]]]],
str]]]) -> Dict[str, List[tuple]]:
"""
:param words: List of dictionaries to be converted
{
'word': word,
'definitions': List of definitions,
'forms': A List of conjugation dictionaries
Conjugation Dictionaries {
'plurality': plural or singular # if this exists then there will be no plurality in the rest of the cases
Each case has a gender suffix separated by a space
'nominative'
'accusative'
'genitive'
'dative'
'instrumental'
Example:
'singular nominative masculine'
or
'nominative masculine' if plurality is defined
}
}
:return: Returns a dictionary with each key corresponding to a table and it's value a list of data to insert
"""
debug('Converting Noun dictionaries')
roots = []
adjectives = []
for w in tqdm(words):
for d in w['definitions']:
roots.append((db_string(w['word']), '"adjective"', db_string(d),
w['word'].startswith('-') or w['word'].endswith('-'))) # Check for affix
for form in w['forms']:
strength = form['strength']
if 'plurality' in form:
# singular form
plurality = form['plurality']
for c, f in form.items():
if c != 'plurality' and c != 'strength':
case, gender = c.split(' ')
adjectives.append((w['word'], db_string(f),
strength == 'strong',
db_string(gender), db_string(case), db_string(plurality)))
else:
for c, f in form.items():
if c != 'strength':
plurality, case, gender = c.split(' ')
adjectives.append((w['word'], db_string(f),
strength == 'strong',
db_string(gender), db_string(case), db_string(plurality)))
return {'old_english_words': roots, 'adjectives': adjectives}
conversion_dict = {
'nouns': convert_word_dictionary_noun,
'verbs': convert_word_dictionary_verb,
'adverbs': convert_word_dictionary_adverb,
'adjectives': convert_word_dictionary_adjectives
}
def initialize_database_scraper():
from soup_targets import soup_targets, wiktionary_root
from controllers.sql import SQLController
from controllers.beautifulsoup import SoupStemScraper, SoupVerbClassScraper, \
SoupAdverbScraper, SoupAdjectiveScraper
cont = SQLController.get_instance()
cont.reset_database()
cont.setup_tables()
noun_declension_tables = set()
verb_conjugation_tables = set()
roots = []
declensions = []
conjugations = []
verbs = []
adverbs = []
adjectives = []
for t, u in soup_targets.items():
words = []
debug('Searching for {}'.format(t))
for s, url in u.items():
debug('Searching for {}'.format(s))
if isinstance(url, dict):
for g, gurl in url.items():
debug('Checking for {}'.format(g))
scraper = None
if t == 'nouns':
scraper = SoupStemScraper(wiktionary_root + '/wiki/' + gurl, s,
initial_table_set=noun_declension_tables)
words += scraper.find_words()
noun_declension_tables = scraper.table_set
elif t == 'verbs':
scraper = SoupVerbClassScraper(wiktionary_root + '/wiki/' + gurl,
initial_table_set=verb_conjugation_tables)
words += [(s, w) for w in scraper.find_words()]
verb_conjugation_tables = scraper.table_set
elif t == 'adverbs':
scraper = SoupAdverbScraper(wiktionary_root + '/wiki/' + gurl, s)
words += [(s, w) for w in scraper.find_words()]
elif t == 'adjectives':
scraper = SoupAdjectiveScraper(wiktionary_root + '/wiki/' + gurl, s)
words += scraper.find_words()
else:
scraper = None
if t == 'nouns':
scraper = SoupStemScraper(wiktionary_root + '/wiki/' + url, s,
initial_table_set=noun_declension_tables)
words += scraper.find_words()
noun_declension_tables = scraper.table_set
elif t == 'verbs':
scraper = SoupVerbClassScraper(wiktionary_root + '/wiki/' + url,
initial_table_set=verb_conjugation_tables)
words += [(s, w) for w in scraper.find_words()]
verb_conjugation_tables = scraper.table_set
elif t == 'adverbs':
scraper = SoupAdverbScraper(wiktionary_root + '/wiki/' + url, s) # There are no tables for adverbs
words += [(s, w) for w in scraper.find_words()]
elif t == 'adjectives':
scraper = SoupAdjectiveScraper(wiktionary_root + '/wiki/' + url, s)
words += scraper.find_words()
debug('Found {} words so far'.format(len(words)))
tuple_dict = conversion_dict[t](words)
if 'old_english_words' in tuple_dict:
roots += tuple_dict['old_english_words']
if 'declensions' in tuple_dict:
declensions += tuple_dict['declensions']
if 'conjugations' in tuple_dict:
conjugations += tuple_dict['conjugations']
if 'verbs' in tuple_dict:
verbs += tuple_dict['verbs']
if 'adverbs' in tuple_dict:
adverbs += tuple_dict['adverbs']
if 'adjectives' in tuple_dict:
adjectives += tuple_dict['adjectives']
cont.insert_record('old_english_words', roots)
insert_declensions(declensions)
insert_verb_conjugations(conjugations)
insert_verb_transitivities(verbs)
insert_adverbs(adverbs)
insert_adjectives(adjectives)
def initialize_database_dump():
cont = SQLController.get_instance()
cont.reset_database()
# debug('Reading English Words')
# with open(modern_english_word_json, 'rb') as fp:
# lines = fp.read().decode('utf8').split('\n')
# tuples = []
# for li, line in enumerate(tqdm(lines[:-1])):
# j = json.loads(line)
# name = '"{}"'.format(j['word'].replace('"', "'"))
# pos = '"{}"'.format(j['pos'].replace('"', "'"))
# for sense in j['senses']:
# conj = True
# if 'form_of' not in sense:
# conj = False
# definition = '"{}"'.format(
# ('. '.join(sense['glosses']) if 'glosses' in sense else '').replace('"', "'"))
# tuples.append((name, pos, definition, li, conj))
# cont.insert_record('english_words', tuples)
debug('Reading Old English Words')
with open(old_english_word_json, 'rb') as fp:
lines = fp.read().decode('utf8').split('\n')
tuples = []
declensions = []
conjugations: List[Tuple[str, str, str, str, str, str, bool, bool]] = []
noun_ipa: List[Tuple[str, str, int, bool]] = []
noun_germ: List[Tuple[str, str, Gender]] = []
for li, line in enumerate(tqdm(lines[:-1])):
j = json.loads(line)
pos = '"{}"'.format(j['pos'].replace('"', "'"))
genders: List[Gender] = []
if 'forms' not in j:
# error('{} has no forms!'.format(j['word']))
name = ['"{}"'.format(j['word'].replace('"', "'"))]
else:
name = ['"{}"'.format(w['form'].replace('"', "'")) for w in j['forms'] if 'canonical' in w['tags']]
for w in j['forms']:
if 'canonical' in w['tags']:
if j['pos'] == 'noun':
for t in w['tags']:
if t in gender_list:
genders.append(Gender[t.upper()])
else:
if j['pos'] == 'noun':
# Maybe a declension?
cases = find_declensions(w['tags'])
for c, p in cases:
for n in name:
declensions.append((n, w['form'], c, p))
for sense in j['senses']:
conj = True
if 'form_of' not in sense:
conj = False
else:
# Detect Declensions
if j['pos'] == 'noun':
cases = find_declensions(sense['tags'])
for c, p in cases:
for f in sense['form_of']:
# debug('{} is the {} {} form of {}'.format(name, c, p, f['word']))
for n in name:
declensions.append((n, f['word'], c, p))
# Detect Conjugations
elif j['pos'] == 'verb':
conjs = find_verb_conjugations(sense['tags'])
for per, pl, t, m, part, pre in conjs:
for f in sense['form_of']:
for n in name:
conjugations.append((n, f['word'], per, pl, t, m, part, pre))
if j['pos'] == 'noun':
# Find IPA for manual declension
if 'sounds' in j:
found = False
for s in j['sounds']:
if 'ipa' in s:
syllables = separate_syllables([s['ipa']])
for n in name:
noun_ipa.append((n, str(s['ipa']),
len(syllables),
bool(re.fullmatch(long_syllable, syllables[-1]) is not None)))
found = True
if not found:
debug('No ipa translation found for {}'.format(j['word']))
else:
debug('No sounds found for {}'.format(j['word']))
# Detect proto-germanic
if 'etymology_templates' in j:
for temp in j['etymology_templates']:
if temp['name'] == 'inh':
# The word was inherited
args = temp['args']
if args['2'] == 'gem-pro':
# And it was inherited from proto germanic
proto = args['3']
for n in name:
for g in genders:
noun_germ.append((n, proto, g))
else:
debug('{} is an OE innovation'.format(j['word']))
definition = '"{}"'.format(
('. '.join(sense['glosses']) if 'glosses' in sense else '').replace('"', "'"))
for n in name:
tuples.append((n, pos, definition, li, conj))
cont.insert_record('old_english_words', tuples)
# Insert Linking Tables
insert_declensions(declensions)
insert_verb_conjugations(conjugations)
insert_ipa(noun_ipa)
insert_proto(noun_germ)
def find_declensions(sense: List[str]) -> List[Tuple[str, str]]:
cases = []
pluralities = []
for tag in sense:
if tag in case_list:
cases.append(tag)
if tag in plurality_list:
pluralities.append(tag)
tuples = []
for c in cases:
for p in pluralities:
tuples.append((c, p))
return tuples
def find_verb_conjugations(sense: List[str]) -> List[Tuple[str, str, str, str, bool, bool]]:
persons = []
pluralities = []
tenses = []
moods = []
participle = False
preterite = False
for tag in sense:
if tag in plurality_list:
pluralities.append(tag)
elif tag in person_list:
persons.append(tag)
elif tag in tense:
tenses.append(tag)
elif tag in mood:
moods.append(tag)
elif tag == 'participle':
participle = True
elif tag == 'preterite':
preterite = True
tuples = []
for a in persons:
for b in pluralities:
for c in tenses:
for d in moods:
tuples.append((a, b, c, d, participle, preterite))
return tuples
def insert_declensions(declensions: List[Tuple[str, str, str, str]]):
cont = SQLController.get_instance()
debug('Inserting Noun Declension Table')
if len(declensions) > 0:
# words = list(set(['"{}"'.format(d[1].replace('"', "'")) for d in declensions] + [d[0] for d in declensions]))
words = list(set(['"{}"'.format(d[1].replace('"', "'")) for d in declensions])) # for scraper style
where_clause = 'name in ({})'.format(','.join(words)) if len(words) > 1 else 'name = {}'.format(words[0])
indices = cont.select_conditional('old_english_words', 'id, name, pos', where_clause)
debug('Generating foreign key dictionary')
pos_dict = {}
index_dict = {}
for index, name, pos in indices:
if name not in index_dict:
index_dict[name] = index
pos_dict[name] = pos
elif pos == 'noun' and pos_dict[name] != 'noun':
index_dict[name] = index
pos_dict[name] = pos
elif pos == 'noun':
debug('Possible ambiguous declension of {} as a {} and {}'.format(name, pos, pos_dict[name]))
debug('linking...')
tuples = []
# for o, w, c, p in declensions:
for w, o, p, c in declensions: # for scraper style
# if w in index_dict:
# # orig = o[1:-1]
# orig = o # for scraper style
# if orig in index_dict:
# tuples.append((w, index_dict[orig], db_string(p), db_string(c)))
# else:
# debug('{} was not found to be a root word'.format(o))
# else:
# debug('{} was not found to be a root word'.format(w))
# For scraper style
orig = o # for scraper style
if orig in index_dict:
tuples.append((w, index_dict[orig], p, c))
else:
debug('{} was not found to be a root word'.format(o))
cont.insert_record('declensions', tuples)
def insert_ipa(declensions: List[Tuple[str, str, int, bool]]):
cont = SQLController.get_instance()
debug('Inserting Noun IPA Table')
words = list(set([d[0] for d in declensions]))
where_clause = 'name in ({})'.format(','.join(words)) if len(words) > 1 else 'name = {}'.format(words[0])
indices = cont.select_conditional('old_english_words', 'id, name, pos', where_clause)
debug('Generating foreign key dictionary')
pos_dict = {}
index_dict = {}
for index, name, pos in indices:
if name not in index_dict:
index_dict[name] = index
pos_dict[name] = pos
elif pos == 'noun' and pos_dict[name] != 'noun':
index_dict[name] = index
pos_dict[name] = pos
elif pos == 'noun':
debug('Possible ambiguous pos of {} as a {} and {}'.format(name, pos, pos_dict[name]))
debug('linking...')
tuples = []
for w, t, c, p in declensions:
w = w[1:-1]
if w in index_dict:
tuples.append(('"{}"'.format(index_dict[w]), '"{}"'.format(t.replace('"', "'")), c, 1 if p else 0))
else:
debug('{} was not found to be a root word'.format(w))
cont.insert_record('ipa', tuples)
def insert_proto(declensions: List[Tuple[str, str, Gender]]):
cont = SQLController.get_instance()
debug('Inserting Noun Proto Germanic Table')
words = list(set([d[0] for d in declensions]))
where_clause = 'name in ({})'.format(','.join(words)) if len(words) > 1 else 'name = {}'.format(words[0])
indices = cont.select_conditional('old_english_words', 'id, name, pos', where_clause)
debug('Generating foreign key dictionary')
pos_dict = {}
index_dict = {}
for index, name, pos in indices:
if name not in index_dict:
index_dict[name] = index
pos_dict[name] = pos
elif pos == 'noun' and pos_dict[name] != 'noun':
index_dict[name] = index
pos_dict[name] = pos
elif pos == 'noun':
debug('Possible ambiguous pos of {} as a {} and {}'.format(name, pos, pos_dict[name]))
debug('linking...')
tuples = []
for w, t, g in declensions:
w = w[1:-1]
if w in index_dict:
tuples.append(('"{}"'.format(index_dict[w]),
'"{}"'.format(t.replace('"', "'")),
'"{}"'.format(g.name.lower())))
else:
debug('{} was not found to be a root word'.format(w))
cont.insert_record('nouns', tuples)
def insert_verb_conjugations(conjugations: List[Tuple[str, str, str, str, str, str, bool, bool]]):
cont = SQLController.get_instance()
debug('Inserting Verb Conjugation Table')
words = list(set([db_string(d[1]) for d in conjugations]))
where_clause = 'name in ({})'.format(','.join(words)) if len(words) > 1 else 'name = {}'.format(words[0])
indices = cont.select_conditional('old_english_words', 'id, name, pos', where_clause)
debug('Generating foreign key dictionary')
pos_dict = {}
index_dict = {}
for index, name, pos in indices:
if name not in index_dict:
index_dict[name] = index
pos_dict[name] = pos
elif pos == 'verb' and pos_dict[name] != 'verb':
index_dict[name] = index
pos_dict[name] = pos
elif pos == 'verb':
debug('Possible ambiguous conjugation of {} as a {} and {}'.format(name, pos, pos_dict[name]))
debug('linking...')
tuples = []
for w, o, per, pl, t, m, pt, pr in conjugations:
if o in index_dict:
tuples.append((w, index_dict[o],
per, pl, t, m,
1 if pt else 0, 1 if pr else 0))
else:
debug('{} was not found to be a root verb'.format(o))
cont.insert_record('conjugations', tuples)
def insert_verb_transitivities(conjugations: List[Tuple[str, bool, int, bool]]):
cont = SQLController.get_instance()
debug('Inserting Verb Conjugation Table')
words = list(set([db_string(d[0]) for d in conjugations]))
where_clause = 'name in ({})'.format(','.join(words)) if len(words) > 1 else 'name = {}'.format(words[0])
indices = cont.select_conditional('old_english_words', 'id, name, pos', where_clause)
debug('Generating foreign key dictionary')
pos_dict = {}
index_dict = {}
for index, name, pos in indices:
if name not in index_dict:
index_dict[name] = index
pos_dict[name] = pos
elif pos == 'verb' and pos_dict[name] != 'verb':
index_dict[name] = index
pos_dict[name] = pos
elif pos == 'verb':
debug('Possible ambiguous conjugation of {} as a {} and {}'.format(name, pos, pos_dict[name]))
debug('linking...')
tuples = []
for w, stren, cl, trans in conjugations:
if w in index_dict:
tuples.append((index_dict[w], 1 if stren else 0, cl, 1 if trans else 0))
else:
debug('{} was not found to be a root verb'.format(w))
cont.insert_record('verbs', tuples)
def insert_adverbs(adverbs: List[Tuple[str, bool, bool]]):
cont = SQLController.get_instance()
debug('Inserting Adverb Table')
words = list(set([db_string(d[0]) for d in adverbs]))
where_clause = 'name in ({})'.format(','.join(words)) if len(words) > 1 else 'name = {}'.format(words[0])
indices = cont.select_conditional('old_english_words', 'id, name, pos', where_clause)
debug('Generating foreign key dictionary')
pos_dict = {}
index_dict = {}
for index, name, pos in indices:
if name not in index_dict:
index_dict[name] = index
pos_dict[name] = pos
elif pos == 'adverb' and pos_dict[name] != 'adverb':
index_dict[name] = index
pos_dict[name] = pos
elif pos == 'adverb':
debug('Possible ambiguous conjugation of {} as a {} and {}'.format(name, pos, pos_dict[name]))
debug('linking...')
tuples = []
for w, comp, sup in adverbs:
if w in index_dict:
tuples.append((index_dict[w], 1 if comp else 0, 1 if sup else 0))
else:
debug('{} was not found to be a root adverb'.format(w))
cont.insert_record('adverbs', tuples)
def insert_adjectives(adverbs: List[Tuple[str, str, bool, str, str, str]]):
cont = SQLController.get_instance()
debug('Inserting Adjective Declension Table')
words = list(set([db_string(d[0]) for d in adverbs]))
where_clause = 'name in ({})'.format(','.join(words)) if len(words) > 1 else 'name = {}'.format(words[0])
indices = cont.select_conditional('old_english_words', 'id, name, pos', where_clause)
debug('Generating foreign key dictionary')
pos_dict = {}
index_dict = {}
for index, name, pos in indices:
if name not in index_dict:
index_dict[name] = index
pos_dict[name] = pos
elif pos == 'adjective' and pos_dict[name] != 'adjective':
index_dict[name] = index
pos_dict[name] = pos
elif pos == 'adjective':
debug('Possible ambiguous conjugation of {} as a {} and {}'.format(name, pos, pos_dict[name]))
debug('linking...')
tuples = []
for w, o, stren, gen, case, plur in adverbs:
if w in index_dict:
tuples.append((index_dict[w], o, 1 if stren else 0, gen, case, plur))
else:
debug('{} was not found to be a root adverb'.format(w))
cont.insert_record('adjectives', tuples)
if __name__ == '__main__':
use_unverified_ssl()
initialize_database_scraper()