-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathipa_parser.py
More file actions
1488 lines (1254 loc) · 49.5 KB
/
Copy pathipa_parser.py
File metadata and controls
1488 lines (1254 loc) · 49.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding: utf-8
"""
IPA_PARSER:
Contains IPAParser class for parsing IPA pronunciation data.
"""
from morpheme_parser import *
class IPAParser(MorphemeParser):
"""
A class for parsing IPA data from Wiktionary in a given language.
"""
def __init__(self, language):
MorphemeParser.__init__(self, language)
self.ipas = set() # this language's IPA symbols
self.vowels = OrderedSet([])
self.consonants = OrderedSet([])
self.phoneme_dict = {}
def merge_dicts(self, first, other):
"""
Merges the first dict with the other dict.
:param first: dict, to merge with other, where...
key (X)
val (OrderedSet(X))
:param other: dict, to merge with first, where...
key (X)
val (OrderedSet(X))
:return: dict, first merged with other, where...
key (X)
val (OrderedSet(X))
"""
first = {phoneme: first[phoneme].union(other.pop(phoneme).pop(phoneme))
for phoneme in first if phoneme in other}
first.update(other)
return first
# HOMOPHONES
# ----------
def nearest_homophones(self, word, language):
"""
Returns the nearest homophones in the given language
to the given word in this IPAParser's native language.
:param word: str, word in IPAParser's native language
:param language: str, language of desired output homophones
:return: List[str], homophones for word in given language
"""
word_ipas = self.word_ipas(word, self.language)
word_ipas = [self.clean_ipa(word_ipa, scrub=True) for word_ipa in word_ipas]
homophones = list()
if len(word_ipas) != 0:
foreign = self.all_ipas(language)
for word_ipa in word_ipas:
homophone = None
for fw in foreign:
ipas = foreign[fw]
if len(ipas) != 0:
ipa = self.clean_ipa(ipas[0], scrub=True)
if homophone is None:
homophone = IPAWord(fw, language, parser=self)
continue
homo = self.nearer_homophone(word_ipa, homophone.get_cleaned_ipa(), ipa)
if homo == ipa:
homophone = IPAWord(fw, language, parser=self)
if word_ipa == ipa:
break
if homophone is not None:
homophones.append(homophone.word)
if len(homophones) == 0:
homophones.append(None)
return homophones
def nearest_homophone(self, word, language):
"""
Returns the nearest homophone in the given language
to the given word in this IPAParser's native language.
~
e.g. nearest_homophone("droit", "English") -> "draw"
:param word: str, word in IPAParser's native language
:param language: str, language of desired output homophone
:return: str, homophone for word in given language
"""
word_ipa = self.word_ipa(word)
homophone = None
if word_ipa is not None:
word_ipa = self.clean_ipa(word_ipa, scrub=True)
foreign = self.all_ipas(language)
for fw in foreign:
ipas = foreign[fw]
if len(ipas) != 0:
ipa = self.clean_ipa(ipas[0], scrub=True)
if homophone is None:
homophone = IPAWord(fw, language, parser=self)
continue
elif word_ipa == ipa:
return fw
else:
homo = self.nearer_homophone(word_ipa, homophone.get_cleaned_ipa(), ipa)
if homo == ipa:
homophone = IPAWord(fw, language, parser=self)
if homophone is not None:
return homophone.word
return homophone
def nearer_homophone(self, ipa, ipa1, ipa2):
"""
If ipa1 is closer to ipa than ipa2,
return ipa1. Otherwise, return ipa2.
:param ipa: unicode, IPA homophones are trying to be like
:param ipa1: str, first IPA to compare to ipa
:param ipa2: str, second IPA to compare to ipa
:return: str, closest homophone to IPA from ipa1 and ipa2
"""
if ipa == ipa1 or ipa == ipa2:
return ipa
else:
sim1, sim2 = 20, 20
ipa_chars = set(ipa)
elt_diffs = lambda i: len(ipa_chars.symmetric_difference(i))/2.0
sim1 -= elt_diffs(ipa1)
sim2 -= elt_diffs(ipa2)
elt_sims = lambda i: len(ipa_chars.intersection(i))/2.0
sim1 += elt_sims(ipa1)
sim2 += elt_sims(ipa2)
sim1 += self.same_ipas(ipa, ipa1)
sim2 += self.same_ipas(ipa, ipa2)
print ipa, "vs", ipa1, ":\t", sim1
print ipa, "vs", ipa2, ":\t", sim2
if sim1 >= sim2:
print "winner:", ipa1
return ipa1
else:
print "winner:", ipa2
return ipa2
def same_ipas(self, ipa1, ipa2):
"""
Returns an integer representing the number of IPA characters
shared at the same indices by ipa1 and ipa2.
:param ipa1: str, first string to compare
:param ipa2: str, second string to compare
:return: int, number of IPA characters shared by ipa1 and ipa2
"""
sims = 0
i = 0
try:
while True:
char1 = ipa1[i]
char2 = ipa2[i]
letter1 = self.ipa_to_ipaletter(char1)
letter2 = self.ipa_to_ipaletter(char2)
if letter1 is None or letter2 is None:
sims += (ipa1[i] == ipa2[i])
else:
add = letter1.compare(letter2)
sims += add
i += 1
except IndexError:
pass
sims -= abs(len(ipa1) - len(ipa2))
return sims
# COMMON IPAS/PHONEMES
# --------------------
def common_ipas(self, lim=50000):
"""
Returns a list of the 50,000 most common morphemes
in this IPAParser's language transcribed to IPA.
:param lim: int, lim <= 50000, number of IPAs to retreive
:return: Set(str), most common IPAs in IPAParser's language
"""
morphemes = self.common_morphemes(lim)
ipas = set()
for morpheme in morphemes:
ipa = self.word_ipa(morpheme)
if ipa is not None:
ipas.add(ipa)
self.refresh_json()
return ipas
def common_ipa_words(self, lim=50000):
"""
Returns a set of IPAWords corresponding to the
Wiktionary entries of this IPAParser's language's most
common words (up to 50,000).
:param lim: int, lim <= 50000, number of words to retrieve
:return: Set(IPAWord), common IPAWords in this IPAParser's language
"""
words = self.common_words(lim)
transcriptions = self.words_ipawords(words)
return transcriptions
def common_phonemes(self, lim=50000):
"""
Returns a dictionary representing ipa_phonemes
for up to the 50,000 most common words in this language
and each of the forms they take.
:param lim: int, lim <= 50000, number of words to retreive
:return: dict, where...
key (str) - phoneme (i.e., short sequence of characters)
val (List[str]) - IPA translations of this language's phoneme
"""
transcriptions = self.common_ipa_words(lim=lim)
phoneme_dict = self.ipa_words_phonemes(transcriptions)
return phoneme_dict
def common_ipa_pairs(self, language=None, lim=50000, only_top=False):
"""
Returns a set of common IPA-pos pairs from Wordnet up to lim.
~
If top is True, this method only adds the top IPA pronunciation
for each word to the list. Otherwise, adds all IPA pronunciations.
:param lim: int, lim <= 50000, number of ipa pairs to retrieve
:param only_top: bool, whether to output only top IPAs or all IPAs
:return: Set(tuple(str,str)), common ipa pairs in MorphemeParser's language
"""
language = self.verify_language(language)
word_pairs = self.common_word_pairs(language, lim)
ipa_pairs = set()
for word, pos in word_pairs:
ipas = self.word_ipas(word, self.language)
if ipas is not None:
for ipa in ipas:
pair = (ipa, pos)
ipa_pairs.add(pair)
if only_top:
break
self.refresh_json()
return ipa_pairs
# IPA/PHONEME MANIPULATION
# ------------------------
def word_ipaword(self, word, language=None):
"""
Returns the given word as an IPAWord.
:param word: str, word to turn into IPAWord
:return: IPAWord, IPAWord corresponding to given word
"""
language = self.verify_language(language)
ipa = self.word_ipa(word)
if ipa is not None:
return IPAWord(word, language, parser=self)
def words_ipawords(self, words, language=None):
"""
Transcribes the words in the given set of words to IPAWords.
:param words: Set(unicode), set of word definitions
:return: Set(IPAWord), IPAWords corresponding to given definitions
"""
language = self.verify_language(language)
ipa_words = set()
for word in words:
ipa_word = self.word_ipaword(word, language)
if ipa_word is not None:
ipa_words.add(ipa_word)
return ipa_words
def word_declension(self, word, language=None):
"""
Returns the declension for the word in the given language.
~
A declension is a dictionary of word inflections, with the
word lemma as the head and each type of inflection as a
different key-value pair.
:param word: str, word to find declension for
:param language: str, language of declension
:return: dict[], where...
key (str) - declension type (e.g. nominative)
val (List[str]) - all word's inflections for given type
"""
language = self.verify_language(language)
declension = self.find_wiktionary_subentry(word, language, u"Declension")
return declension
def words_declensions(self, words, language=None):
"""
Returns a list of declension dictionaries for each
word (in the given language) in words.
:param words: List[str], words to retrieve declensions for
:param language: str, language of given words
:return: List[dict], declension dictionaries for all words
"""
declensions = []
for word in words:
declension = self.word_declension(word, language)
if declension is not None:
declensions.append(declension)
return declensions
def ipa_to_ipaletter(self, ipa):
try:
return IPALETTERS[ipa]
except KeyError:
return
def ipa_words_to_dict(self, ipa_words):
"""
Returns the given set of IPAWords as a dictionary,
where each IPAWord's word is a key with an associated
IPA pronunciation value.
:param ipa_words: Set(IPAWord)
:return: dict, where...
key (unicode) - IPAWord's word
val (unicode) - IPA pronunciation of IPAWord
"""
ipa_dict = {}
word_count = 1 # start word numbers at 1
for ipa_word in ipa_words:
word_dict = ipa_word.get_dict()
for key in word_dict:
key_num = key + str(word_count)
ipa_dict[key_num] = word_dict[key]
word_count += 1
return ipa_dict
def ipa_words_phonemes(self, ipa_words):
"""
Returns a dictionary representing all phonemes in ipa_words.
~
N.B. Phonemes are in a language's native lettering system,
while their forms are in IPA.
:param ipa_words: Set(IPAWord), IPAWords to return phonemes of
:return: dict, where...
key (str) - phoneme (i.e., short sequence of >=1 characters)
val (List[str]) - IPA translations of this language's phoneme
"""
ipa_words = sorted(ipa_words, key=lambda iw: iw.get_difficulty())
for ipa_word in ipa_words:
phoneme_dict = ipa_word.find_phoneme_dict()
self.phoneme_dict = self.merge_dicts(self.phoneme_dict, phoneme_dict)
return self.phoneme_dict
def next_phoneme(self, ipa, remove=True, use_syllables=True):
"""
Returns the given ipa's next phoneme.
~
If remove is set to True, this method finds and
removes ipa's first phoneme, returning a 2-tuple of
1) the phoneme and 2) given ipa with phoneme removed.
~
e.g. next_phoneme("ɔˈba.lat͡ɕ") -> ("ɔ", "balat͡ɕ")
:param ipa: unicode, IPA word to return next phoneme of
:param remove: bool, whether to return ipa with vowels removed
:param use_syllables: bool, whether to calculate next phoneme with ipa's syllables
:return: tuple((both unicode) str, str), IPA's first phoneme and rest of IPA
"""
phoneme = str() # next phoneme so far
if len(ipa) == 0:
next_phoneme = (phoneme, ipa) if remove else phoneme
return next_phoneme
if use_syllables:
# ensure uniform stress marks
new_ipa = self.restress(ipa)
# end ipa @ 1st syllable marker
new_ipa = new_ipa.split(u".", 1)[0]
else:
new_ipa = self.clean_ipa(ipa)
# search for polyphonemes first
end = 1
# TODO: change to end <= min([longest IPA phoneme in phoneme_dict], len(new_ipa))
while end <= 3:
new_sym = new_ipa[:end]
filtered_sym = "".join(filter((lambda x: x if x not in SEMIVOWELS else ""), new_sym))
# check to make sure phonemes are all vowels xor all consonants
are_vowels = self.is_ipa_vowel(filtered_sym)
if are_vowels is None:
end -= 1
break
elif self.is_ipa_phoneme(new_sym):
phoneme = new_sym
end += 1
# if no polyphonemes found,
# set phoneme to first IPA character
if len(phoneme) == 0:
phoneme = new_ipa[0]
end = 1
next_phoneme = (phoneme, ipa[end:]) if remove else phoneme
return next_phoneme
# VOWELS, CONSONANTS, & PHONEMES
# ------------------------------
def is_letter_vowel(self, chars):
"""
Returns True if the given chars is a vowel in this
IPAWord's native language, False if a consonant.
~
Returns None if chars is not in this IPAParser's phoneme_dict.
~
N.B. chars can be multiple letters long.
:param chars: unicode, character(s) to determine whether vowel
:return: bool, whether given character(s) are a vowel
"""
if chars in self.phoneme_dict:
return chars in self.vowels.get_items()
def is_letter_consonant(self, chars):
"""
Returns True if the given chars is a consonant in this
IPAWord's native language, False if a vowel.
~
Returns None if this chars is not in this IPAParser's phoneme_dict.
~
N.B. chars can be multiple letters long.
:param chars: unicode, character(s) to determine whether consonant
:return: bool, whether given character(s) are a consonant
"""
if chars in self.phoneme_dict:
return chars in self.consonants.get_items()
def is_letter_phoneme(self, chars):
"""
Returns True if the given chars is a phoneme in this
IPAWord's native language, False otherwise.
~
Returns None if this chars is not in this IPAParser's phoneme_dict.
~
N.B. chars can be multiple letters long.
:param chars: unicode, character(s) to determine whether phoneme
:return: bool, whether given character(s) are a phoneme
"""
return chars in self.phoneme_dict
def is_ipa_vowel(self, ipa):
"""
Returns True if the given IPA symbol is a vowel
according to the IPA, False if a consonant.
~
Returns None if this symbol is not an IPA letter.
:param ipa: unicode, IPA symbol to determine whether vowel
:return: bool, whether given IPA symbol is a vowel
"""
try:
ipa_sym = IPALETTERS[ipa]
except KeyError:
if len(ipa) > 1:
ipa_phonemes = self.phoneme_dict.keys()
if len(ipa_phonemes) == 0:
return
elif ipa in ipa_phonemes:
return any(self.is_ipa_vowel(sym) for sym in ipa if sym in IPALETTERS)
else:
return
else:
return ipa_sym.is_vowel
def is_ipa_semivowel(self, ipa):
"""
Returns True if the given IPA symbol is a semivowel
according to the IPA, False otherwise.
~
Returns None if this symbol is not an IPA letter.
:param ipa: unicode, IPA symbol to determine whether vowel
:return: bool, whether given IPA symbol is a vowel
"""
try:
IPALETTERS[ipa]
except KeyError:
return None
else:
return ipa in SEMIVOWELS
def is_ipa_phoneme(self, ipa):
"""
Returns True if the given IPA symbol is a phoneme in the
IPA or in this IPAParser's language, False otherwise.
:param ipa: unicode, IPA symbol to determine whether phoneme
:return: bool, whether given IPA symbol is a phoneme
"""
for phoneme in self.phoneme_dict:
items = self.phoneme_dict[phoneme]
for item in iter(items):
if ipa == item:
return True
else:
if self.is_ipa_vowel(ipa) is not None:
return True
else:
return False
def add_vowel(self, chars):
"""
Adds the given chars to this IPAParser's
list of vowels.
:param chars: str, phoneme (i.e., short sequence of characters)
:return: None
"""
self.vowels.add(chars)
def add_consonant(self, chars):
"""
Adds the given chars to this IPAParser's
list of consonants.
:param chars: str, phoneme (i.e., short sequence of characters)
:return: None
"""
self.consonants.add(chars)
def add_phoneme_entry(self, chars, ipas):
"""
Adds the given chars-ipas pair to this IPAParser's
phoneme_dict.
:param chars: str, phoneme (i.e., short sequence of characters)
:param ipas: str, IPA translation of this language's phoneme
:return: None
"""
self.phoneme_dict.setdefault(chars, OrderedSet([]))
self.phoneme_dict[chars].add(ipas)
def destress(self, ipa):
"""
Returns the given IPA pronunciation with stress marks removed.
:param ipa: unicode, IPA to remove stress marks from
:return: unicode, ipa with stress marks removed
"""
return re.sub(u"[" + self.STRESS_MARKS + u"]", u"", ipa)
def restress(self, ipa):
"""
Returns the given IPA pronunciation with all stress marks
replaced with periods.
:param ipa: unicode, IPA to replace stress marks with periods
:return: unicode, ipa with stress marks replaced with periods
"""
restressed = re.sub(u"[" + self.STRESS_MARKS + u"]", u".", ipa)
return restressed.strip(u".")
class IPAWord:
"""
A class for operating on words and their IPA pronunciations.
"""
def __init__(self, word, language, pos=None, parser=None):
self.language = language
if parser is None:
self.parser = IPAParser(self.language)
else:
self.parser = parser
self.word = word
self.pos = pos
self.vowels = OrderedSet([])
self.consonants = OrderedSet([])
self.ipa = None
self.phoneme_dict = {}
#self.word_model = self.build_word_model(self.word)
#self.ipa_model = self.build_ipa_model(self.ipa)
#self.difficulty = self.difficulty_score()
#self.find_phoneme_dict(self.word, self.ipa)
def get_word(self):
"""
Returns this IPAWord's word, in its native language's alphabet.
:return: str, this IPAWord's word
"""
return self.parser.clean_word(self.word)
def get_pos(self):
"""
Returns this IPAWord's part-of-speech, pos.
:return: str, this IPAWord's part-of-speech
"""
return self.pos
def get_ipa(self):
"""
Returns this IPAWord's pronunciation in IPA.
:return: str, this IPAWord's IPA pronunciation
"""
if self.ipa is None:
self.init_ipa()
return self.ipa
def init_ipa(self):
"""
Initializes this IPAWord's IPA according to its word and language.
:return:
"""
self.ipa = self.parser.word_ipa(self.word, self.language)
def get_cleaned_ipa(self, scrub=True):
"""
Returns this IPAWord's pronunciation in IPA,
with no stress symbols.
:param scrub: bool, whether to also remove diacritics
:return: str, this IPAWord's IPA pronunciation
"""
return self.parser.clean_ipa(self.get_ipa(), scrub=scrub)
def get_phoneme_dict(self):
"""
Returns this IPAWord's phoneme dictionary.
:return: dict, where...
key (str) - >=1 letters in a native language alphabet
val (Set(str)) - list of >=1 IPA symbols corresponding to key
"""
return self.phoneme_dict
def get_difficulty(self):
return self.difficulty
def init_phoneme_dict(self):
"""
Initializes this IPAWord's phoneme dictionary.
:return: dict, where...
key (str) - >=1 letters in a native language alphabet
val (Set(str)) - list of >=1 IPA symbols corresponding to key
"""
self.phoneme_dict = self.find_phoneme_dict()
def set_pos(self, pos):
"""
Sets given pos to this IPAWord's part-of-speech.
:param pos: str, this IPAWord's part-of-speech
:return: None
"""
self.pos = pos
def add_phoneme_entry(self, chars, ipas):
"""
Adds the given chars-ipas pair to this IPAWord and IPAParser's
phoneme_dict.
:param chars: str, phoneme (i.e., short sequence of characters)
:param ipas: str, IPA translation of this language's phoneme
:return: None
"""
self.phoneme_dict.setdefault(chars, OrderedSet([]))
self.phoneme_dict[chars].add(ipas)
if self.parser.is_ipa_vowel(ipas):
self.add_vowel(chars)
if self.parser.is_ipa_vowel(ipas) is False or any(self.parser.is_ipa_vowel(ipa) is False for ipa in ipas):
self.add_consonant(chars)
self.parser.add_phoneme_entry(chars, ipas)
def add_vowel(self, chars):
"""
Adds the given chars to this IPAWord and IPAParser's
list of vowels.
:param chars: str, phoneme (i.e., short sequence of characters)
:return: None
"""
self.vowels.add(chars)
self.parser.add_vowel(chars)
def add_consonant(self, chars):
"""
Adds the given chars to this IPAWord and IPAParser's
list of consonants.
:param chars: str, phoneme (i.e., short sequence of characters)
:return: None
"""
self.consonants.add(chars)
self.parser.add_consonant(chars)
def find_vowels(self, phrase, remove=True):
"""
Returns the first continuous string of vowels in
the given phrase.
~
If remove is set to True, this method finds and removes
the first string of vowels, returning a tuple of the
vowels and the given phrase after the vowels.
~
e.g. find_vowels("stroop", remove=False) -> "oo"
find_vowels("stroop", remove=True) -> ("oo", "p")
:param phrase: str, phrase to extract vowels from
:param remove: bool, whether to return phrase with vowels removed
:return: str, first string of vowels in phrase
"""
pre_vowels = True
vowels = unicode(u"")
char_idx = 0
for char in phrase:
if pre_vowels:
if self.parser.is_letter_vowel(char) is True:
pre_vowels = False
vowels += char
else:
if self.parser.is_letter_vowel(char) is not False:
vowels += char
else:
break
char_idx += 1
if remove:
remainder = phrase[char_idx:]
return (vowels, remainder)
else:
return vowels
def find_consonants(self, phrase, remove=True):
"""
Returns the first continuous string of consonants in
the given phrase.
~
If remove is set to True, this method finds and removes
the first string of consonants, returning a tuple.
~
e.g. find_consonants("stroop", remove=False) -> "str"
find_consonants("stroop", remove=True) -> ("str", "oop")
:param phrase: str, phrase to extract consonants from
:param remove: bool, whether to return phrase with consonants removed
:return: str, first string of consonants in phrase
or tuple(str, str), first string of consonants in phrase and
phrase with consonants removed
"""
pre_consonants = True
consonants = unicode()
char_idx = 0
for char in phrase:
if pre_consonants:
if self.parser.is_letter_vowel(char) is False:
pre_consonants = False
consonants += char
else:
if self.parser.is_letter_vowel(char) is True:
phoneme2 = consonants[-2:]
if self.parser.is_letter_consonant(phoneme2):
consonants = consonants[:-2]
char_idx -= 2
else:
consonants = consonants[:-1]
char_idx -= 1
break
else:
consonants += char
char_idx += 1
if remove:
remainder = phrase[char_idx:]
return (consonants, remainder)
else:
return consonants
def find_ipa_vowels(self, ipa, remove=True):
"""
Returns the first continuous string of vowels in
the given IPA.
~
If remove is set to True, this method finds and removes
the first string of vowels, returning a tuple of the
vowels and the given IPA after the vowels.
~
e.g. find_vowels("twɔk", remove=False) -> "ɔ"
find_vowels("twɔk", remove=True) -> ("ɔ", "k")
:param ipa: (unicode) str, IPA to extract vowels from
:param remove: bool, whether to return phrase with vowels removed
:return: (unicode) str, first string of vowels in IPA
"""
ipa = self.parser.restress(ipa)
pre_vowels = True
vowels = unicode()
sym_idx = 0
for sym in ipa:
if pre_vowels:
if self.parser.is_ipa_vowel(sym):
pre_vowels = False
vowels += sym
else:
if self.parser.is_ipa_vowel(sym):
vowels += sym
else:
if sym == u".":
sym_idx += 1
break
sym_idx += 1
if remove:
remainder = ipa[sym_idx:]
return (vowels, remainder)
else:
return vowels
def find_ipa_consonants(self, ipa, remove=True):
"""
Returns the first continuous string of consonants in
the given IPA.
~
If remove is set to True, this method finds and removes
the first string of consonants, returning a tuple of the
consonants and the given IPA after the consonants.
~
e.g. find_consonants("twɔk", remove=False) -> "tw"
find_consonants("twɔk", remove=True) -> ("tw", "ɔk")
:param ipa: (unicode) str, IPA to extract consonants from
:param remove: bool, whether to return phrase with consonants removed
:return: (unicode) str, first string of consonants in IPA
"""
ipa = self.parser.restress(ipa)
pre_consonants = True
consonants = unicode()
sym_idx = 0
for sym in ipa:
is_vowel = self.parser.is_ipa_vowel(sym)
if pre_consonants:
if is_vowel is False:
pre_consonants = False
consonants += sym
else:
if is_vowel:
sym_idx -= 1
consonants = consonants[:sym_idx]
sym_idx += 1
break
else:
if sym == u".":
sym_idx += 1
break
else:
consonants += sym
sym_idx += 1
if remove:
remainder = ipa[sym_idx:]
return (consonants, remainder)
else:
return consonants
def find_letter_phonemes(self):
"""
Returns this IPAWord's letter phonemes as a list of
character strings.
~
Phonemes are calculated from this IPAWord's word as well as ipa.
~
e.g. cat = IPAWord("cat", "Noun", "kæt", IPAParser("English"))
cat.find_letter_phonemes() -> ["c", "a", "t"]
text = IPAWord("text", "Noun", "tɛkst", IPAParser("English"))
text.find_letter_phonemes() -> ["t", "e", "x", "t"]
:return: List[(unicode) str], this IPAWord's letter phonemes
"""
cleaned_ipa = self.get_cleaned_ipa()
phonemes = []
size = len(cleaned_ipa)
start = 0 # inclusive
end = 1 # exclusive
while end <= size:
if end != size and cleaned_ipa[end] in SYMBOLS:
if cleaned_ipa[end] in AFFRICATES:
end += 1 # skip 2 for affricates
end += 1 # skip 1 for diacritics
else:
phoneme = cleaned_ipa[start:end]
phonemes.append(phoneme)
start = end
end = start + 1
return phonemes
def extract_vowels(self, ipas):
"""
Breaks the given ipas into a list of IPA vowels.
~
Assumes ipas contains no consonants.
:param ipas: (unicode) str, IPA to break into a list of vowels
:return: List[(unicode) str], IPA broken into vowels
"""
phonemes = []
ipas_iter = iter(range(len(ipas)))
for i in ipas_iter:
try:
ipas[i+2]
except IndexError:
pass
else:
phone_2 = ipas[i:i+2]
if self.parser.is_ipa_vowel(phone_2):
phonemes.append(phone_2)
next(ipas_iter)
continue
phone_1 = ipas[i]
if self.parser.is_ipa_vowel(phone_1):
phonemes.append(phone_1)
continue
try:
ipas[i+3]
except IndexError:
pass
else:
phone_3 = ipas[i:i+3]
if self.parser.is_ipa_vowel(phone_3):
phonemes.append(phone_3)
next(ipas_iter)
next(ipas_iter)
continue
phonemes.append(phone_1)
return phonemes
def extract_consonants(self, ipas):
"""
Breaks the given ipas into a list of IPA consonants.
~
Assumes ipas contains no vowels.
:param ipas: (unicode) str, IPA to break into a list of consonants
:return: List[(unicode) str], IPA broken into consonants
"""
phonemes = []
ipas_iter = iter(range(len(ipas)))
for i in ipas_iter:
try:
phone_1 = ipas[i:i+1]
except IndexError: