id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
230,400
cltk/cltk
cltk/corpus/punjabi/numerifier.py
englishToPun_number
def englishToPun_number(number): """This function converts the normal english number to the punjabi number with punjabi digits, its input will be an integer of type int, and output will be a string. """ output = '' number = list(str(number)) for digit in number: output += DIGITS[int(digit)] return output
python
def englishToPun_number(number): output = '' number = list(str(number)) for digit in number: output += DIGITS[int(digit)] return output
[ "def", "englishToPun_number", "(", "number", ")", ":", "output", "=", "''", "number", "=", "list", "(", "str", "(", "number", ")", ")", "for", "digit", "in", "number", ":", "output", "+=", "DIGITS", "[", "int", "(", "digit", ")", "]", "return", "outp...
This function converts the normal english number to the punjabi number with punjabi digits, its input will be an integer of type int, and output will be a string.
[ "This", "function", "converts", "the", "normal", "english", "number", "to", "the", "punjabi", "number", "with", "punjabi", "digits", "its", "input", "will", "be", "an", "integer", "of", "type", "int", "and", "output", "will", "be", "a", "string", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/punjabi/numerifier.py#L19-L28
230,401
cltk/cltk
cltk/corpus/sanskrit/itrans/langinfo.py
is_indiclang_char
def is_indiclang_char(c,lang): """ Applicable to Brahmi derived Indic scripts """ o=get_offset(c,lang) return (o>=0 and o<=0x7f) or ord(c)==DANDA or ord(c)==DOUBLE_DANDA
python
def is_indiclang_char(c,lang): o=get_offset(c,lang) return (o>=0 and o<=0x7f) or ord(c)==DANDA or ord(c)==DOUBLE_DANDA
[ "def", "is_indiclang_char", "(", "c", ",", "lang", ")", ":", "o", "=", "get_offset", "(", "c", ",", "lang", ")", "return", "(", "o", ">=", "0", "and", "o", "<=", "0x7f", ")", "or", "ord", "(", "c", ")", "==", "DANDA", "or", "ord", "(", "c", "...
Applicable to Brahmi derived Indic scripts
[ "Applicable", "to", "Brahmi", "derived", "Indic", "scripts" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/sanskrit/itrans/langinfo.py#L98-L103
230,402
cltk/cltk
cltk/corpus/sanskrit/itrans/langinfo.py
is_velar
def is_velar(c,lang): """ Is the character a velar """ o=get_offset(c,lang) return (o>=VELAR_RANGE[0] and o<=VELAR_RANGE[1])
python
def is_velar(c,lang): o=get_offset(c,lang) return (o>=VELAR_RANGE[0] and o<=VELAR_RANGE[1])
[ "def", "is_velar", "(", "c", ",", "lang", ")", ":", "o", "=", "get_offset", "(", "c", ",", "lang", ")", "return", "(", "o", ">=", "VELAR_RANGE", "[", "0", "]", "and", "o", "<=", "VELAR_RANGE", "[", "1", "]", ")" ]
Is the character a velar
[ "Is", "the", "character", "a", "velar" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/sanskrit/itrans/langinfo.py#L147-L152
230,403
cltk/cltk
cltk/corpus/sanskrit/itrans/langinfo.py
is_palatal
def is_palatal(c,lang): """ Is the character a palatal """ o=get_offset(c,lang) return (o>=PALATAL_RANGE[0] and o<=PALATAL_RANGE[1])
python
def is_palatal(c,lang): o=get_offset(c,lang) return (o>=PALATAL_RANGE[0] and o<=PALATAL_RANGE[1])
[ "def", "is_palatal", "(", "c", ",", "lang", ")", ":", "o", "=", "get_offset", "(", "c", ",", "lang", ")", "return", "(", "o", ">=", "PALATAL_RANGE", "[", "0", "]", "and", "o", "<=", "PALATAL_RANGE", "[", "1", "]", ")" ]
Is the character a palatal
[ "Is", "the", "character", "a", "palatal" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/sanskrit/itrans/langinfo.py#L154-L159
230,404
cltk/cltk
cltk/corpus/sanskrit/itrans/langinfo.py
is_retroflex
def is_retroflex(c,lang): """ Is the character a retroflex """ o=get_offset(c,lang) return (o>=RETROFLEX_RANGE[0] and o<=RETROFLEX_RANGE[1])
python
def is_retroflex(c,lang): o=get_offset(c,lang) return (o>=RETROFLEX_RANGE[0] and o<=RETROFLEX_RANGE[1])
[ "def", "is_retroflex", "(", "c", ",", "lang", ")", ":", "o", "=", "get_offset", "(", "c", ",", "lang", ")", "return", "(", "o", ">=", "RETROFLEX_RANGE", "[", "0", "]", "and", "o", "<=", "RETROFLEX_RANGE", "[", "1", "]", ")" ]
Is the character a retroflex
[ "Is", "the", "character", "a", "retroflex" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/sanskrit/itrans/langinfo.py#L161-L166
230,405
cltk/cltk
cltk/corpus/sanskrit/itrans/langinfo.py
is_dental
def is_dental(c,lang): """ Is the character a dental """ o=get_offset(c,lang) return (o>=DENTAL_RANGE[0] and o<=DENTAL_RANGE[1])
python
def is_dental(c,lang): o=get_offset(c,lang) return (o>=DENTAL_RANGE[0] and o<=DENTAL_RANGE[1])
[ "def", "is_dental", "(", "c", ",", "lang", ")", ":", "o", "=", "get_offset", "(", "c", ",", "lang", ")", "return", "(", "o", ">=", "DENTAL_RANGE", "[", "0", "]", "and", "o", "<=", "DENTAL_RANGE", "[", "1", "]", ")" ]
Is the character a dental
[ "Is", "the", "character", "a", "dental" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/sanskrit/itrans/langinfo.py#L168-L173
230,406
cltk/cltk
cltk/corpus/sanskrit/itrans/langinfo.py
is_labial
def is_labial(c,lang): """ Is the character a labial """ o=get_offset(c,lang) return (o>=LABIAL_RANGE[0] and o<=LABIAL_RANGE[1])
python
def is_labial(c,lang): o=get_offset(c,lang) return (o>=LABIAL_RANGE[0] and o<=LABIAL_RANGE[1])
[ "def", "is_labial", "(", "c", ",", "lang", ")", ":", "o", "=", "get_offset", "(", "c", ",", "lang", ")", "return", "(", "o", ">=", "LABIAL_RANGE", "[", "0", "]", "and", "o", "<=", "LABIAL_RANGE", "[", "1", "]", ")" ]
Is the character a labial
[ "Is", "the", "character", "a", "labial" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/sanskrit/itrans/langinfo.py#L175-L180
230,407
cltk/cltk
cltk/prosody/middle_high_german/verse.py
Verse.to_phonetics
def to_phonetics(self): """Transcribe phonetics.""" tr = Transcriber() self.transcribed_phonetics = [tr.transcribe(line) for line in self.text]
python
def to_phonetics(self): tr = Transcriber() self.transcribed_phonetics = [tr.transcribe(line) for line in self.text]
[ "def", "to_phonetics", "(", "self", ")", ":", "tr", "=", "Transcriber", "(", ")", "self", ".", "transcribed_phonetics", "=", "[", "tr", ".", "transcribe", "(", "line", ")", "for", "line", "in", "self", ".", "text", "]" ]
Transcribe phonetics.
[ "Transcribe", "phonetics", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/middle_high_german/verse.py#L15-L18
230,408
cltk/cltk
cltk/phonology/orthophonology.py
PositionedPhoneme
def PositionedPhoneme(phoneme, word_initial = False, word_final = False, syllable_initial = False, syllable_final = False, env_start = False, env_end = False): ''' A decorator for phonemes, used in applying rules over words. Returns a copy of the input phoneme, with additional attributes, specifying whether the phoneme occurs at a word or syllable boundary, or its position in an environment. ''' pos_phoneme = deepcopy(phoneme) pos_phoneme.word_initial = word_initial pos_phoneme.word_final = word_final pos_phoneme.syllable_initial = syllable_initial pos_phoneme.syllable_final = syllable_final pos_phoneme.env_start = env_start pos_phoneme.env_end = env_end return pos_phoneme
python
def PositionedPhoneme(phoneme, word_initial = False, word_final = False, syllable_initial = False, syllable_final = False, env_start = False, env_end = False): ''' A decorator for phonemes, used in applying rules over words. Returns a copy of the input phoneme, with additional attributes, specifying whether the phoneme occurs at a word or syllable boundary, or its position in an environment. ''' pos_phoneme = deepcopy(phoneme) pos_phoneme.word_initial = word_initial pos_phoneme.word_final = word_final pos_phoneme.syllable_initial = syllable_initial pos_phoneme.syllable_final = syllable_final pos_phoneme.env_start = env_start pos_phoneme.env_end = env_end return pos_phoneme
[ "def", "PositionedPhoneme", "(", "phoneme", ",", "word_initial", "=", "False", ",", "word_final", "=", "False", ",", "syllable_initial", "=", "False", ",", "syllable_final", "=", "False", ",", "env_start", "=", "False", ",", "env_end", "=", "False", ")", ":"...
A decorator for phonemes, used in applying rules over words. Returns a copy of the input phoneme, with additional attributes, specifying whether the phoneme occurs at a word or syllable boundary, or its position in an environment.
[ "A", "decorator", "for", "phonemes", "used", "in", "applying", "rules", "over", "words", ".", "Returns", "a", "copy", "of", "the", "input", "phoneme", "with", "additional", "attributes", "specifying", "whether", "the", "phoneme", "occurs", "at", "a", "word", ...
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/phonology/orthophonology.py#L266-L285
230,409
cltk/cltk
cltk/phonology/orthophonology.py
PhonemeDisjunction.matches
def matches(self, other): ''' A disjunctive list matches a phoneme if any of its members matches the phoneme. If other is also a disjunctive list, any match between this list and the other returns true. ''' if other is None: return False if isinstance(other, PhonemeDisjunction): return any([phoneme.matches(other) for phoneme in self]) if isinstance(other, list) or isinstance(other, PhonologicalFeature): other = phoneme(other) return any([phoneme <= other for phoneme in self])
python
def matches(self, other): ''' A disjunctive list matches a phoneme if any of its members matches the phoneme. If other is also a disjunctive list, any match between this list and the other returns true. ''' if other is None: return False if isinstance(other, PhonemeDisjunction): return any([phoneme.matches(other) for phoneme in self]) if isinstance(other, list) or isinstance(other, PhonologicalFeature): other = phoneme(other) return any([phoneme <= other for phoneme in self])
[ "def", "matches", "(", "self", ",", "other", ")", ":", "if", "other", "is", "None", ":", "return", "False", "if", "isinstance", "(", "other", ",", "PhonemeDisjunction", ")", ":", "return", "any", "(", "[", "phoneme", ".", "matches", "(", "other", ")", ...
A disjunctive list matches a phoneme if any of its members matches the phoneme. If other is also a disjunctive list, any match between this list and the other returns true.
[ "A", "disjunctive", "list", "matches", "a", "phoneme", "if", "any", "of", "its", "members", "matches", "the", "phoneme", ".", "If", "other", "is", "also", "a", "disjunctive", "list", "any", "match", "between", "this", "list", "and", "the", "other", "return...
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/phonology/orthophonology.py#L364-L375
230,410
cltk/cltk
cltk/phonology/orthophonology.py
Orthophonology.transcribe
def transcribe(self, text, as_phonemes = False): ''' Trascribes a text, which is first tokenized for words, then each word is transcribed. If as_phonemes is true, returns a list of list of phoneme objects, else returns a string concatenation of the IPA symbols of the phonemes. ''' phoneme_words = [self.transcribe_word(word) for word in self._tokenize(text)] if not as_phonemes: words = [''.join([phoneme.ipa for phoneme in word]) for word in phoneme_words] return ' '.join(words) else: return phoneme_words
python
def transcribe(self, text, as_phonemes = False): ''' Trascribes a text, which is first tokenized for words, then each word is transcribed. If as_phonemes is true, returns a list of list of phoneme objects, else returns a string concatenation of the IPA symbols of the phonemes. ''' phoneme_words = [self.transcribe_word(word) for word in self._tokenize(text)] if not as_phonemes: words = [''.join([phoneme.ipa for phoneme in word]) for word in phoneme_words] return ' '.join(words) else: return phoneme_words
[ "def", "transcribe", "(", "self", ",", "text", ",", "as_phonemes", "=", "False", ")", ":", "phoneme_words", "=", "[", "self", ".", "transcribe_word", "(", "word", ")", "for", "word", "in", "self", ".", "_tokenize", "(", "text", ")", "]", "if", "not", ...
Trascribes a text, which is first tokenized for words, then each word is transcribed. If as_phonemes is true, returns a list of list of phoneme objects, else returns a string concatenation of the IPA symbols of the phonemes.
[ "Trascribes", "a", "text", "which", "is", "first", "tokenized", "for", "words", "then", "each", "word", "is", "transcribed", ".", "If", "as_phonemes", "is", "true", "returns", "a", "list", "of", "list", "of", "phoneme", "objects", "else", "returns", "a", "...
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/phonology/orthophonology.py#L733-L744
230,411
cltk/cltk
cltk/phonology/orthophonology.py
Orthophonology.transcribe_to_modern
def transcribe_to_modern(self, text) : ''' A very first attempt at trancribing from IPA to some modern orthography. The method is intended to provide the student with clues to the pronounciation of old orthographies. ''' # first transcribe letter by letter phoneme_words = self.transcribe(text, as_phonemes = True) words = [''.join([self.to_modern[0][phoneme.ipa] for phoneme in word]) for word in phoneme_words] modern_text = ' '.join(words) # then apply phonotactic fixes for regexp, replacement in self.to_modern[1]: modern_text = re.sub(regexp, replacement, modern_text) return modern_text
python
def transcribe_to_modern(self, text) : ''' A very first attempt at trancribing from IPA to some modern orthography. The method is intended to provide the student with clues to the pronounciation of old orthographies. ''' # first transcribe letter by letter phoneme_words = self.transcribe(text, as_phonemes = True) words = [''.join([self.to_modern[0][phoneme.ipa] for phoneme in word]) for word in phoneme_words] modern_text = ' '.join(words) # then apply phonotactic fixes for regexp, replacement in self.to_modern[1]: modern_text = re.sub(regexp, replacement, modern_text) return modern_text
[ "def", "transcribe_to_modern", "(", "self", ",", "text", ")", ":", "# first transcribe letter by letter\r", "phoneme_words", "=", "self", ".", "transcribe", "(", "text", ",", "as_phonemes", "=", "True", ")", "words", "=", "[", "''", ".", "join", "(", "[", "s...
A very first attempt at trancribing from IPA to some modern orthography. The method is intended to provide the student with clues to the pronounciation of old orthographies.
[ "A", "very", "first", "attempt", "at", "trancribing", "from", "IPA", "to", "some", "modern", "orthography", ".", "The", "method", "is", "intended", "to", "provide", "the", "student", "with", "clues", "to", "the", "pronounciation", "of", "old", "orthographies",...
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/phonology/orthophonology.py#L746-L760
230,412
cltk/cltk
cltk/phonology/orthophonology.py
Orthophonology.voice
def voice(self, consonant) : ''' Voices a consonant, by searching the sound inventory for a consonant having the same features as the argument, but +voice. ''' voiced_consonant = deepcopy(consonant) voiced_consonant[Voiced] = Voiced.pos return self._find_sound(voiced_consonant)
python
def voice(self, consonant) : ''' Voices a consonant, by searching the sound inventory for a consonant having the same features as the argument, but +voice. ''' voiced_consonant = deepcopy(consonant) voiced_consonant[Voiced] = Voiced.pos return self._find_sound(voiced_consonant)
[ "def", "voice", "(", "self", ",", "consonant", ")", ":", "voiced_consonant", "=", "deepcopy", "(", "consonant", ")", "voiced_consonant", "[", "Voiced", "]", "=", "Voiced", ".", "pos", "return", "self", ".", "_find_sound", "(", "voiced_consonant", ")" ]
Voices a consonant, by searching the sound inventory for a consonant having the same features as the argument, but +voice.
[ "Voices", "a", "consonant", "by", "searching", "the", "sound", "inventory", "for", "a", "consonant", "having", "the", "same", "features", "as", "the", "argument", "but", "+", "voice", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/phonology/orthophonology.py#L764-L771
230,413
cltk/cltk
cltk/phonology/orthophonology.py
Orthophonology.aspirate
def aspirate(self, consonant) : ''' Aspirates a consonant, by searching the sound inventory for a consonant having the same features as the argument, but +aspirated. ''' aspirated_consonant = deepcopy(consonant) aspirated_consonant[Aspirated] = Aspirated.pos return self._find_sound(aspirated_consonant)
python
def aspirate(self, consonant) : ''' Aspirates a consonant, by searching the sound inventory for a consonant having the same features as the argument, but +aspirated. ''' aspirated_consonant = deepcopy(consonant) aspirated_consonant[Aspirated] = Aspirated.pos return self._find_sound(aspirated_consonant)
[ "def", "aspirate", "(", "self", ",", "consonant", ")", ":", "aspirated_consonant", "=", "deepcopy", "(", "consonant", ")", "aspirated_consonant", "[", "Aspirated", "]", "=", "Aspirated", ".", "pos", "return", "self", ".", "_find_sound", "(", "aspirated_consonant...
Aspirates a consonant, by searching the sound inventory for a consonant having the same features as the argument, but +aspirated.
[ "Aspirates", "a", "consonant", "by", "searching", "the", "sound", "inventory", "for", "a", "consonant", "having", "the", "same", "features", "as", "the", "argument", "but", "+", "aspirated", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/phonology/orthophonology.py#L773-L780
230,414
cltk/cltk
cltk/tokenize/utils.py
BaseSentenceTokenizerTrainer.train_sentence_tokenizer
def train_sentence_tokenizer(self: object, text: str): """ Train sentence tokenizer. """ language_punkt_vars = PunktLanguageVars # Set punctuation if self.punctuation: if self.strict: language_punkt_vars.sent_end_chars = self.punctuation + self.strict_punctuation else: language_punkt_vars.sent_end_chars = self.punctuation # Set abbreviations trainer = PunktTrainer(text, language_punkt_vars) trainer.INCLUDE_ALL_COLLOCS = True trainer.INCLUDE_ABBREV_COLLOCS = True tokenizer = PunktSentenceTokenizer(trainer.get_params()) if self.abbreviations: for abbreviation in self.abbreviations: tokenizer._params.abbrev_types.add(abbreviation) return tokenizer
python
def train_sentence_tokenizer(self: object, text: str): language_punkt_vars = PunktLanguageVars # Set punctuation if self.punctuation: if self.strict: language_punkt_vars.sent_end_chars = self.punctuation + self.strict_punctuation else: language_punkt_vars.sent_end_chars = self.punctuation # Set abbreviations trainer = PunktTrainer(text, language_punkt_vars) trainer.INCLUDE_ALL_COLLOCS = True trainer.INCLUDE_ABBREV_COLLOCS = True tokenizer = PunktSentenceTokenizer(trainer.get_params()) if self.abbreviations: for abbreviation in self.abbreviations: tokenizer._params.abbrev_types.add(abbreviation) return tokenizer
[ "def", "train_sentence_tokenizer", "(", "self", ":", "object", ",", "text", ":", "str", ")", ":", "language_punkt_vars", "=", "PunktLanguageVars", "# Set punctuation", "if", "self", ".", "punctuation", ":", "if", "self", ".", "strict", ":", "language_punkt_vars", ...
Train sentence tokenizer.
[ "Train", "sentence", "tokenizer", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/tokenize/utils.py#L44-L68
230,415
cltk/cltk
cltk/corpus/readers.py
FilteredPlaintextCorpusReader.docs
def docs(self, fileids=None) -> Generator[str, str, None]: """ Returns the complete text of an Text document, closing the document after we are done reading it and yielding it in a memory safe fashion. """ if not fileids: fileids = self.fileids() # Create a generator, loading one document into memory at a time. for path, encoding in self.abspaths(fileids, include_encoding=True): with codecs.open(path, 'r', encoding=encoding) as reader: if self.skip_keywords: tmp_data = [] for line in reader: skip = False for keyword in self.skip_keywords: if keyword in line: skip = True if not skip: tmp_data.append(line) yield ''.join(tmp_data) else: yield reader.read()
python
def docs(self, fileids=None) -> Generator[str, str, None]: if not fileids: fileids = self.fileids() # Create a generator, loading one document into memory at a time. for path, encoding in self.abspaths(fileids, include_encoding=True): with codecs.open(path, 'r', encoding=encoding) as reader: if self.skip_keywords: tmp_data = [] for line in reader: skip = False for keyword in self.skip_keywords: if keyword in line: skip = True if not skip: tmp_data.append(line) yield ''.join(tmp_data) else: yield reader.read()
[ "def", "docs", "(", "self", ",", "fileids", "=", "None", ")", "->", "Generator", "[", "str", ",", "str", ",", "None", "]", ":", "if", "not", "fileids", ":", "fileids", "=", "self", ".", "fileids", "(", ")", "# Create a generator, loading one document into ...
Returns the complete text of an Text document, closing the document after we are done reading it and yielding it in a memory safe fashion.
[ "Returns", "the", "complete", "text", "of", "an", "Text", "document", "closing", "the", "document", "after", "we", "are", "done", "reading", "it", "and", "yielding", "it", "in", "a", "memory", "safe", "fashion", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/readers.py#L211-L232
230,416
cltk/cltk
cltk/corpus/readers.py
FilteredPlaintextCorpusReader.sizes
def sizes(self, fileids=None) -> Generator[int, int, None]: """ Returns a list of tuples, the fileid and size on disk of the file. This function is used to detect oddly large files in the corpus. """ if not fileids: fileids = self.fileids() # Create a generator, getting every path and computing filesize for path in self.abspaths(fileids): yield os.path.getsize(path)
python
def sizes(self, fileids=None) -> Generator[int, int, None]: if not fileids: fileids = self.fileids() # Create a generator, getting every path and computing filesize for path in self.abspaths(fileids): yield os.path.getsize(path)
[ "def", "sizes", "(", "self", ",", "fileids", "=", "None", ")", "->", "Generator", "[", "int", ",", "int", ",", "None", "]", ":", "if", "not", "fileids", ":", "fileids", "=", "self", ".", "fileids", "(", ")", "# Create a generator, getting every path and co...
Returns a list of tuples, the fileid and size on disk of the file. This function is used to detect oddly large files in the corpus.
[ "Returns", "a", "list", "of", "tuples", "the", "fileid", "and", "size", "on", "disk", "of", "the", "file", ".", "This", "function", "is", "used", "to", "detect", "oddly", "large", "files", "in", "the", "corpus", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/readers.py#L234-L243
230,417
cltk/cltk
cltk/corpus/readers.py
TesseraeCorpusReader.docs
def docs(self: object, fileids:str): """ Returns the complete text of a .tess file, closing the document after we are done reading it and yielding it in a memory-safe fashion. """ for path, encoding in self.abspaths(fileids, include_encoding=True): with codecs.open(path, 'r', encoding=encoding) as f: yield f.read()
python
def docs(self: object, fileids:str): for path, encoding in self.abspaths(fileids, include_encoding=True): with codecs.open(path, 'r', encoding=encoding) as f: yield f.read()
[ "def", "docs", "(", "self", ":", "object", ",", "fileids", ":", "str", ")", ":", "for", "path", ",", "encoding", "in", "self", ".", "abspaths", "(", "fileids", ",", "include_encoding", "=", "True", ")", ":", "with", "codecs", ".", "open", "(", "path"...
Returns the complete text of a .tess file, closing the document after we are done reading it and yielding it in a memory-safe fashion.
[ "Returns", "the", "complete", "text", "of", "a", ".", "tess", "file", "closing", "the", "document", "after", "we", "are", "done", "reading", "it", "and", "yielding", "it", "in", "a", "memory", "-", "safe", "fashion", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/readers.py#L410-L418
230,418
cltk/cltk
cltk/corpus/readers.py
TesseraeCorpusReader.lines
def lines(self: object, fileids: str, plaintext: bool = True): """ Tokenizes documents in the corpus by line """ for text in self.texts(fileids, plaintext): text = re.sub(r'\n\s*\n', '\n', text, re.MULTILINE) # Remove blank lines for line in text.split('\n'): yield line
python
def lines(self: object, fileids: str, plaintext: bool = True): for text in self.texts(fileids, plaintext): text = re.sub(r'\n\s*\n', '\n', text, re.MULTILINE) # Remove blank lines for line in text.split('\n'): yield line
[ "def", "lines", "(", "self", ":", "object", ",", "fileids", ":", "str", ",", "plaintext", ":", "bool", "=", "True", ")", ":", "for", "text", "in", "self", ".", "texts", "(", "fileids", ",", "plaintext", ")", ":", "text", "=", "re", ".", "sub", "(...
Tokenizes documents in the corpus by line
[ "Tokenizes", "documents", "in", "the", "corpus", "by", "line" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/readers.py#L444-L452
230,419
cltk/cltk
cltk/corpus/readers.py
TesseraeCorpusReader.sents
def sents(self: object, fileids: str): """ Tokenizes documents in the corpus by sentence """ for para in self.paras(fileids): for sent in sent_tokenize(para): yield sent
python
def sents(self: object, fileids: str): for para in self.paras(fileids): for sent in sent_tokenize(para): yield sent
[ "def", "sents", "(", "self", ":", "object", ",", "fileids", ":", "str", ")", ":", "for", "para", "in", "self", ".", "paras", "(", "fileids", ")", ":", "for", "sent", "in", "sent_tokenize", "(", "para", ")", ":", "yield", "sent" ]
Tokenizes documents in the corpus by sentence
[ "Tokenizes", "documents", "in", "the", "corpus", "by", "sentence" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/readers.py#L454-L461
230,420
cltk/cltk
cltk/corpus/readers.py
TesseraeCorpusReader.words
def words(self: object, fileids: str): """ Tokenizes documents in the corpus by word """ for sent in self.sents(fileids): for token in word_tokenize(sent): yield token
python
def words(self: object, fileids: str): for sent in self.sents(fileids): for token in word_tokenize(sent): yield token
[ "def", "words", "(", "self", ":", "object", ",", "fileids", ":", "str", ")", ":", "for", "sent", "in", "self", ".", "sents", "(", "fileids", ")", ":", "for", "token", "in", "word_tokenize", "(", "sent", ")", ":", "yield", "token" ]
Tokenizes documents in the corpus by word
[ "Tokenizes", "documents", "in", "the", "corpus", "by", "word" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/readers.py#L463-L469
230,421
cltk/cltk
cltk/corpus/readers.py
TesseraeCorpusReader.pos_tokenize
def pos_tokenize(self: object, fileids: str): """ Segments, tokenizes, and POS tag a document in the corpus. """ for para in self.paras(fileids): yield [ self.pos_tagger(word_tokenize(sent)) for sent in sent_tokenize(para) ]
python
def pos_tokenize(self: object, fileids: str): for para in self.paras(fileids): yield [ self.pos_tagger(word_tokenize(sent)) for sent in sent_tokenize(para) ]
[ "def", "pos_tokenize", "(", "self", ":", "object", ",", "fileids", ":", "str", ")", ":", "for", "para", "in", "self", ".", "paras", "(", "fileids", ")", ":", "yield", "[", "self", ".", "pos_tagger", "(", "word_tokenize", "(", "sent", ")", ")", "for",...
Segments, tokenizes, and POS tag a document in the corpus.
[ "Segments", "tokenizes", "and", "POS", "tag", "a", "document", "in", "the", "corpus", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/readers.py#L471-L479
230,422
cltk/cltk
cltk/corpus/readers.py
TesseraeCorpusReader.describe
def describe(self: object, fileids: str = None): """ Performs a single pass of the corpus and returns a dictionary with a variety of metrics concerning the state of the corpus. based on (Bengfort et al, 2018: 46) """ started = time.time() # Structures to perform counting counts = FreqDist() tokens = FreqDist() # Perform a single pass over paragraphs, tokenize, and counts for para in self.paras(fileids): counts['paras'] += 1 for sent in para: counts['sents'] += 1 # Include POS at some point for word in sent: counts['words'] += 1 tokens[word] += 1 # Compute the number of files in the corpus n_fileids = len(self.fileids()) # Return data structure with information return { 'files': n_fileids, 'paras': counts['paras'], 'sents': counts['sents'], 'words': counts['words'], 'vocab': len(tokens), 'lexdiv': round((counts['words'] / len(tokens)), 3), 'ppdoc': round((counts['paras'] / n_fileids), 3), 'sppar':round((counts['sents'] / counts['paras']), 3), 'secs': round((time.time()-started), 3), }
python
def describe(self: object, fileids: str = None): started = time.time() # Structures to perform counting counts = FreqDist() tokens = FreqDist() # Perform a single pass over paragraphs, tokenize, and counts for para in self.paras(fileids): counts['paras'] += 1 for sent in para: counts['sents'] += 1 # Include POS at some point for word in sent: counts['words'] += 1 tokens[word] += 1 # Compute the number of files in the corpus n_fileids = len(self.fileids()) # Return data structure with information return { 'files': n_fileids, 'paras': counts['paras'], 'sents': counts['sents'], 'words': counts['words'], 'vocab': len(tokens), 'lexdiv': round((counts['words'] / len(tokens)), 3), 'ppdoc': round((counts['paras'] / n_fileids), 3), 'sppar':round((counts['sents'] / counts['paras']), 3), 'secs': round((time.time()-started), 3), }
[ "def", "describe", "(", "self", ":", "object", ",", "fileids", ":", "str", "=", "None", ")", ":", "started", "=", "time", ".", "time", "(", ")", "# Structures to perform counting", "counts", "=", "FreqDist", "(", ")", "tokens", "=", "FreqDist", "(", ")",...
Performs a single pass of the corpus and returns a dictionary with a variety of metrics concerning the state of the corpus. based on (Bengfort et al, 2018: 46)
[ "Performs", "a", "single", "pass", "of", "the", "corpus", "and", "returns", "a", "dictionary", "with", "a", "variety", "of", "metrics", "concerning", "the", "state", "of", "the", "corpus", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/readers.py#L481-L520
230,423
cltk/cltk
cltk/lemmatize/french/lemma.py
LemmaReplacer._load_entries
def _load_entries(self): """Check for availability of lemmatizer for French.""" rel_path = os.path.join('~','cltk_data', 'french', 'text','french_data_cltk' ,'entries.py') path = os.path.expanduser(rel_path) #logger.info('Loading entries. This may take a minute.') loader = importlib.machinery.SourceFileLoader('entries', path) module = loader.load_module() entries = module.entries return entries
python
def _load_entries(self): rel_path = os.path.join('~','cltk_data', 'french', 'text','french_data_cltk' ,'entries.py') path = os.path.expanduser(rel_path) #logger.info('Loading entries. This may take a minute.') loader = importlib.machinery.SourceFileLoader('entries', path) module = loader.load_module() entries = module.entries return entries
[ "def", "_load_entries", "(", "self", ")", ":", "rel_path", "=", "os", ".", "path", ".", "join", "(", "'~'", ",", "'cltk_data'", ",", "'french'", ",", "'text'", ",", "'french_data_cltk'", ",", "'entries.py'", ")", "path", "=", "os", ".", "path", ".", "e...
Check for availability of lemmatizer for French.
[ "Check", "for", "availability", "of", "lemmatizer", "for", "French", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/lemmatize/french/lemma.py#L19-L31
230,424
cltk/cltk
cltk/lemmatize/french/lemma.py
LemmaReplacer.lemmatize
def lemmatize(self, tokens): """define list of lemmas""" entries = self.entries forms_and_lemmas = self.forms_and_lemmas lemma_list = [x[0] for x in entries] """Provide a lemma for each token""" lemmatized = [] for token in tokens: """check for a match between token and list of lemmas""" if token in lemma_list: lemmed = (token, token) lemmatized.append(lemmed) else: """if no match check for a match between token and list of lemma forms""" lemma = [k for k, v in forms_and_lemmas.items() if token in v] if lemma != []: lemmed = (token, lemma) lemmatized.append(lemmed) elif lemma == []: """if no match apply regular expressions and check for a match against the list of lemmas again""" regexed = regex(token) if regexed in lemma_list: lemmed = (token, regexed) lemmatized.append(lemmed) else: lemmed = (token, "None") lemmatized.append(lemmed) return lemmatized
python
def lemmatize(self, tokens): entries = self.entries forms_and_lemmas = self.forms_and_lemmas lemma_list = [x[0] for x in entries] """Provide a lemma for each token""" lemmatized = [] for token in tokens: """check for a match between token and list of lemmas""" if token in lemma_list: lemmed = (token, token) lemmatized.append(lemmed) else: """if no match check for a match between token and list of lemma forms""" lemma = [k for k, v in forms_and_lemmas.items() if token in v] if lemma != []: lemmed = (token, lemma) lemmatized.append(lemmed) elif lemma == []: """if no match apply regular expressions and check for a match against the list of lemmas again""" regexed = regex(token) if regexed in lemma_list: lemmed = (token, regexed) lemmatized.append(lemmed) else: lemmed = (token, "None") lemmatized.append(lemmed) return lemmatized
[ "def", "lemmatize", "(", "self", ",", "tokens", ")", ":", "entries", "=", "self", ".", "entries", "forms_and_lemmas", "=", "self", ".", "forms_and_lemmas", "lemma_list", "=", "[", "x", "[", "0", "]", "for", "x", "in", "entries", "]", "\"\"\"Provide a lemma...
define list of lemmas
[ "define", "list", "of", "lemmas" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/lemmatize/french/lemma.py#L46-L74
230,425
cltk/cltk
cltk/tokenize/sentence.py
BaseSentenceTokenizer.tokenize
def tokenize(self, text: str, model: object = None): """ Method for tokenizing sentences with pretrained punkt models; can be overridden by language-specific tokenizers. :rtype: list :param text: text to be tokenized into sentences :type text: str :param model: tokenizer object to used # Should be in init? :type model: object """ if not self.model: model = self.model tokenizer = self.model if self.lang_vars: tokenizer._lang_vars = self.lang_vars return tokenizer.tokenize(text)
python
def tokenize(self, text: str, model: object = None): if not self.model: model = self.model tokenizer = self.model if self.lang_vars: tokenizer._lang_vars = self.lang_vars return tokenizer.tokenize(text)
[ "def", "tokenize", "(", "self", ",", "text", ":", "str", ",", "model", ":", "object", "=", "None", ")", ":", "if", "not", "self", ".", "model", ":", "model", "=", "self", ".", "model", "tokenizer", "=", "self", ".", "model", "if", "self", ".", "l...
Method for tokenizing sentences with pretrained punkt models; can be overridden by language-specific tokenizers. :rtype: list :param text: text to be tokenized into sentences :type text: str :param model: tokenizer object to used # Should be in init? :type model: object
[ "Method", "for", "tokenizing", "sentences", "with", "pretrained", "punkt", "models", ";", "can", "be", "overridden", "by", "language", "-", "specific", "tokenizers", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/tokenize/sentence.py#L33-L50
230,426
cltk/cltk
cltk/tokenize/sentence.py
BaseRegexSentenceTokenizer.tokenize
def tokenize(self, text: str, model: object = None): """ Method for tokenizing sentences with regular expressions. :rtype: list :param text: text to be tokenized into sentences :type text: str """ sentences = re.split(self.pattern, text) return sentences
python
def tokenize(self, text: str, model: object = None): sentences = re.split(self.pattern, text) return sentences
[ "def", "tokenize", "(", "self", ",", "text", ":", "str", ",", "model", ":", "object", "=", "None", ")", ":", "sentences", "=", "re", ".", "split", "(", "self", ".", "pattern", ",", "text", ")", "return", "sentences" ]
Method for tokenizing sentences with regular expressions. :rtype: list :param text: text to be tokenized into sentences :type text: str
[ "Method", "for", "tokenizing", "sentences", "with", "regular", "expressions", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/tokenize/sentence.py#L96-L105
230,427
cltk/cltk
cltk/lemmatize/old_english/lemma.py
OldEnglishDictionaryLemmatizer._load_forms_and_lemmas
def _load_forms_and_lemmas(self): """Load the dictionary of lemmas and forms from the OE models repository.""" rel_path = os.path.join(CLTK_DATA_DIR, 'old_english', 'model', 'old_english_models_cltk', 'data', 'oe.lemmas') path = os.path.expanduser(rel_path) self.lemma_dict = {} with open(path, 'r') as infile: lines = infile.read().splitlines() for line in lines: forms = line.split('\t') lemma = forms[0] for form_seq in forms: indiv_forms = form_seq.split(',') for form in indiv_forms: form = form.lower() lemma_list = self.lemma_dict.get(form, []) lemma_list.append(lemma) self.lemma_dict[form] = lemma_list for form in self.lemma_dict.keys(): self.lemma_dict[form] = list(set(self.lemma_dict[form]))
python
def _load_forms_and_lemmas(self): rel_path = os.path.join(CLTK_DATA_DIR, 'old_english', 'model', 'old_english_models_cltk', 'data', 'oe.lemmas') path = os.path.expanduser(rel_path) self.lemma_dict = {} with open(path, 'r') as infile: lines = infile.read().splitlines() for line in lines: forms = line.split('\t') lemma = forms[0] for form_seq in forms: indiv_forms = form_seq.split(',') for form in indiv_forms: form = form.lower() lemma_list = self.lemma_dict.get(form, []) lemma_list.append(lemma) self.lemma_dict[form] = lemma_list for form in self.lemma_dict.keys(): self.lemma_dict[form] = list(set(self.lemma_dict[form]))
[ "def", "_load_forms_and_lemmas", "(", "self", ")", ":", "rel_path", "=", "os", ".", "path", ".", "join", "(", "CLTK_DATA_DIR", ",", "'old_english'", ",", "'model'", ",", "'old_english_models_cltk'", ",", "'data'", ",", "'oe.lemmas'", ")", "path", "=", "os", ...
Load the dictionary of lemmas and forms from the OE models repository.
[ "Load", "the", "dictionary", "of", "lemmas", "and", "forms", "from", "the", "OE", "models", "repository", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/lemmatize/old_english/lemma.py#L18-L46
230,428
cltk/cltk
cltk/lemmatize/old_english/lemma.py
OldEnglishDictionaryLemmatizer._load_type_counts
def _load_type_counts(self): """Load the table of frequency counts of word forms.""" rel_path = os.path.join(CLTK_DATA_DIR, 'old_english', 'model', 'old_english_models_cltk', 'data', 'oe.counts') path = os.path.expanduser(rel_path) self.type_counts = {} with open(path, 'r') as infile: lines = infile.read().splitlines() for line in lines: count, word = line.split() self.type_counts[word] = int(count)
python
def _load_type_counts(self): rel_path = os.path.join(CLTK_DATA_DIR, 'old_english', 'model', 'old_english_models_cltk', 'data', 'oe.counts') path = os.path.expanduser(rel_path) self.type_counts = {} with open(path, 'r') as infile: lines = infile.read().splitlines() for line in lines: count, word = line.split() self.type_counts[word] = int(count)
[ "def", "_load_type_counts", "(", "self", ")", ":", "rel_path", "=", "os", ".", "path", ".", "join", "(", "CLTK_DATA_DIR", ",", "'old_english'", ",", "'model'", ",", "'old_english_models_cltk'", ",", "'data'", ",", "'oe.counts'", ")", "path", "=", "os", ".", ...
Load the table of frequency counts of word forms.
[ "Load", "the", "table", "of", "frequency", "counts", "of", "word", "forms", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/lemmatize/old_english/lemma.py#L49-L66
230,429
cltk/cltk
cltk/lemmatize/old_english/lemma.py
OldEnglishDictionaryLemmatizer._relative_frequency
def _relative_frequency(self, word): """Computes the log relative frequency for a word form""" count = self.type_counts.get(word, 0) return math.log(count/len(self.type_counts)) if count > 0 else 0
python
def _relative_frequency(self, word): count = self.type_counts.get(word, 0) return math.log(count/len(self.type_counts)) if count > 0 else 0
[ "def", "_relative_frequency", "(", "self", ",", "word", ")", ":", "count", "=", "self", ".", "type_counts", ".", "get", "(", "word", ",", "0", ")", "return", "math", ".", "log", "(", "count", "/", "len", "(", "self", ".", "type_counts", ")", ")", "...
Computes the log relative frequency for a word form
[ "Computes", "the", "log", "relative", "frequency", "for", "a", "word", "form" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/lemmatize/old_english/lemma.py#L68-L72
230,430
cltk/cltk
cltk/lemmatize/old_english/lemma.py
OldEnglishDictionaryLemmatizer._lemmatize_token
def _lemmatize_token(self, token, best_guess=True, return_frequencies=False): """Lemmatize a single token. If best_guess is true, then take the most frequent lemma when a form has multiple possible lemmatizations. If the form is not found, just return it. If best_guess is false, then always return the full set of possible lemmas, or None if none found. """ lemmas = self.lemma_dict.get(token.lower(), None) if best_guess == True: if lemmas == None: lemma = token elif len(lemmas) > 1: counts = [self.type_counts[word] for word in lemmas] lemma = lemmas[argmax(counts)] else: lemma = lemmas[0] if return_frequencies == True: lemma = (lemma, self._relative_frequency(lemma)) else: lemma = [] if lemmas == None else lemmas if return_frequencies == True: lemma = [(word, self._relative_frequency(word)) for word in lemma] return(token, lemma)
python
def _lemmatize_token(self, token, best_guess=True, return_frequencies=False): lemmas = self.lemma_dict.get(token.lower(), None) if best_guess == True: if lemmas == None: lemma = token elif len(lemmas) > 1: counts = [self.type_counts[word] for word in lemmas] lemma = lemmas[argmax(counts)] else: lemma = lemmas[0] if return_frequencies == True: lemma = (lemma, self._relative_frequency(lemma)) else: lemma = [] if lemmas == None else lemmas if return_frequencies == True: lemma = [(word, self._relative_frequency(word)) for word in lemma] return(token, lemma)
[ "def", "_lemmatize_token", "(", "self", ",", "token", ",", "best_guess", "=", "True", ",", "return_frequencies", "=", "False", ")", ":", "lemmas", "=", "self", ".", "lemma_dict", ".", "get", "(", "token", ".", "lower", "(", ")", ",", "None", ")", "if",...
Lemmatize a single token. If best_guess is true, then take the most frequent lemma when a form has multiple possible lemmatizations. If the form is not found, just return it. If best_guess is false, then always return the full set of possible lemmas, or None if none found.
[ "Lemmatize", "a", "single", "token", ".", "If", "best_guess", "is", "true", "then", "take", "the", "most", "frequent", "lemma", "when", "a", "form", "has", "multiple", "possible", "lemmatizations", ".", "If", "the", "form", "is", "not", "found", "just", "r...
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/lemmatize/old_english/lemma.py#L74-L98
230,431
cltk/cltk
cltk/lemmatize/old_english/lemma.py
OldEnglishDictionaryLemmatizer.lemmatize
def lemmatize(self, text, best_guess=True, return_frequencies=False): """Lemmatize all tokens in a string or a list. A string is first tokenized using punkt. Throw a type error if the input is neither a string nor a list. """ if isinstance(text, str): tokens = wordpunct_tokenize(text) elif isinstance(text, list): tokens= text else: raise TypeError("lemmatize only works with strings or lists of string tokens.") return [self._lemmatize_token(token, best_guess, return_frequencies) for token in tokens]
python
def lemmatize(self, text, best_guess=True, return_frequencies=False): if isinstance(text, str): tokens = wordpunct_tokenize(text) elif isinstance(text, list): tokens= text else: raise TypeError("lemmatize only works with strings or lists of string tokens.") return [self._lemmatize_token(token, best_guess, return_frequencies) for token in tokens]
[ "def", "lemmatize", "(", "self", ",", "text", ",", "best_guess", "=", "True", ",", "return_frequencies", "=", "False", ")", ":", "if", "isinstance", "(", "text", ",", "str", ")", ":", "tokens", "=", "wordpunct_tokenize", "(", "text", ")", "elif", "isinst...
Lemmatize all tokens in a string or a list. A string is first tokenized using punkt. Throw a type error if the input is neither a string nor a list.
[ "Lemmatize", "all", "tokens", "in", "a", "string", "or", "a", "list", ".", "A", "string", "is", "first", "tokenized", "using", "punkt", ".", "Throw", "a", "type", "error", "if", "the", "input", "is", "neither", "a", "string", "nor", "a", "list", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/lemmatize/old_english/lemma.py#L100-L111
230,432
cltk/cltk
cltk/lemmatize/old_english/lemma.py
OldEnglishDictionaryLemmatizer.evaluate
def evaluate(self, filename): """Runs the lemmatize function over the contents of the file, counting the proportion of unfound lemmas.""" with open(filename, 'r') as infile: lines = infile.read().splitlines() lemma_count = 0 token_count = 0 for line in lines: line = re.sub(r'[.,!?:;0-9]', ' ', line) lemmas = [lemma for (_, lemma) in self.lemmatize(line, best_guess=False)] token_count += len(lemmas) lemma_count += len(lemmas) - lemmas.count([]) return lemma_count/token_count
python
def evaluate(self, filename): with open(filename, 'r') as infile: lines = infile.read().splitlines() lemma_count = 0 token_count = 0 for line in lines: line = re.sub(r'[.,!?:;0-9]', ' ', line) lemmas = [lemma for (_, lemma) in self.lemmatize(line, best_guess=False)] token_count += len(lemmas) lemma_count += len(lemmas) - lemmas.count([]) return lemma_count/token_count
[ "def", "evaluate", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "infile", ":", "lines", "=", "infile", ".", "read", "(", ")", ".", "splitlines", "(", ")", "lemma_count", "=", "0", "token_count", "=",...
Runs the lemmatize function over the contents of the file, counting the proportion of unfound lemmas.
[ "Runs", "the", "lemmatize", "function", "over", "the", "contents", "of", "the", "file", "counting", "the", "proportion", "of", "unfound", "lemmas", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/lemmatize/old_english/lemma.py#L113-L128
230,433
cltk/cltk
cltk/stem/akkadian/stem.py
Stemmer.get_stem
def get_stem(self, noun, gender, mimation=True): """Return the stem of a noun, given its gender""" stem = '' if mimation and noun[-1:] == 'm': # noun = noun[:-1] pass # Take off ending if gender == 'm': if noun[-2:] in list(self.endings['m']['singular'].values()) + \ list(self.endings['m']['dual'].values()): stem = noun[:-2] elif noun[-1] in list(self.endings['m']['plural'].values()): stem = noun[:-1] else: print("Unknown masculine noun: {}".format(noun)) elif gender == 'f': if noun[-4:] in self.endings['f']['plural']['nominative'] + \ self.endings['f']['plural']['oblique']: stem = noun[:-4] + 't' elif noun[-3:] in list(self.endings['f']['singular'].values()) + \ list(self.endings['f']['dual'].values()): stem = noun[:-3] + 't' elif noun[-2:] in list(self.endings['m']['singular'].values()) + \ list(self.endings['m']['dual'].values()): stem = noun[:-2] else: print("Unknown feminine noun: {}".format(noun)) else: print("Unknown noun: {}".format(noun)) return stem
python
def get_stem(self, noun, gender, mimation=True): stem = '' if mimation and noun[-1:] == 'm': # noun = noun[:-1] pass # Take off ending if gender == 'm': if noun[-2:] in list(self.endings['m']['singular'].values()) + \ list(self.endings['m']['dual'].values()): stem = noun[:-2] elif noun[-1] in list(self.endings['m']['plural'].values()): stem = noun[:-1] else: print("Unknown masculine noun: {}".format(noun)) elif gender == 'f': if noun[-4:] in self.endings['f']['plural']['nominative'] + \ self.endings['f']['plural']['oblique']: stem = noun[:-4] + 't' elif noun[-3:] in list(self.endings['f']['singular'].values()) + \ list(self.endings['f']['dual'].values()): stem = noun[:-3] + 't' elif noun[-2:] in list(self.endings['m']['singular'].values()) + \ list(self.endings['m']['dual'].values()): stem = noun[:-2] else: print("Unknown feminine noun: {}".format(noun)) else: print("Unknown noun: {}".format(noun)) return stem
[ "def", "get_stem", "(", "self", ",", "noun", ",", "gender", ",", "mimation", "=", "True", ")", ":", "stem", "=", "''", "if", "mimation", "and", "noun", "[", "-", "1", ":", "]", "==", "'m'", ":", "# noun = noun[:-1]", "pass", "# Take off ending", "if", ...
Return the stem of a noun, given its gender
[ "Return", "the", "stem", "of", "a", "noun", "given", "its", "gender" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/stem/akkadian/stem.py#L50-L79
230,434
cltk/cltk
cltk/prosody/latin/macronizer.py
Macronizer._retrieve_tag
def _retrieve_tag(self, text): """Tag text with chosen tagger and clean tags. Tag format: [('word', 'tag')] :param text: string :return: list of tuples, with each tuple containing the word and its pos tag :rtype : list """ if self.tagger == 'tag_ngram_123_backoff': # Data format: Perseus Style (see https://github.com/cltk/latin_treebank_perseus) tags = POSTag('latin').tag_ngram_123_backoff(text.lower()) return [(tag[0], tag[1]) for tag in tags] elif self.tagger == 'tag_tnt': tags = POSTag('latin').tag_tnt(text.lower()) return [(tag[0], tag[1]) for tag in tags] elif self.tagger == 'tag_crf': tags = POSTag('latin').tag_crf(text.lower()) return [(tag[0], tag[1]) for tag in tags]
python
def _retrieve_tag(self, text): if self.tagger == 'tag_ngram_123_backoff': # Data format: Perseus Style (see https://github.com/cltk/latin_treebank_perseus) tags = POSTag('latin').tag_ngram_123_backoff(text.lower()) return [(tag[0], tag[1]) for tag in tags] elif self.tagger == 'tag_tnt': tags = POSTag('latin').tag_tnt(text.lower()) return [(tag[0], tag[1]) for tag in tags] elif self.tagger == 'tag_crf': tags = POSTag('latin').tag_crf(text.lower()) return [(tag[0], tag[1]) for tag in tags]
[ "def", "_retrieve_tag", "(", "self", ",", "text", ")", ":", "if", "self", ".", "tagger", "==", "'tag_ngram_123_backoff'", ":", "# Data format: Perseus Style (see https://github.com/cltk/latin_treebank_perseus)", "tags", "=", "POSTag", "(", "'latin'", ")", ".", "tag_ngra...
Tag text with chosen tagger and clean tags. Tag format: [('word', 'tag')] :param text: string :return: list of tuples, with each tuple containing the word and its pos tag :rtype : list
[ "Tag", "text", "with", "chosen", "tagger", "and", "clean", "tags", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/macronizer.py#L49-L66
230,435
cltk/cltk
cltk/prosody/latin/macronizer.py
Macronizer._retrieve_morpheus_entry
def _retrieve_morpheus_entry(self, word): """Return Morpheus entry for word Entry format: [(head word, tag, macronized form)] :param word: unmacronized, lowercased word :ptype word: string :return: Morpheus entry in tuples :rtype : list """ entry = self.macron_data.get(word) if entry is None: logger.info('No Morpheus entry found for {}.'.format(word)) return None elif len(entry) == 0: logger.info('No Morpheus entry found for {}.'.format(word)) return entry
python
def _retrieve_morpheus_entry(self, word): entry = self.macron_data.get(word) if entry is None: logger.info('No Morpheus entry found for {}.'.format(word)) return None elif len(entry) == 0: logger.info('No Morpheus entry found for {}.'.format(word)) return entry
[ "def", "_retrieve_morpheus_entry", "(", "self", ",", "word", ")", ":", "entry", "=", "self", ".", "macron_data", ".", "get", "(", "word", ")", "if", "entry", "is", "None", ":", "logger", ".", "info", "(", "'No Morpheus entry found for {}.'", ".", "format", ...
Return Morpheus entry for word Entry format: [(head word, tag, macronized form)] :param word: unmacronized, lowercased word :ptype word: string :return: Morpheus entry in tuples :rtype : list
[ "Return", "Morpheus", "entry", "for", "word" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/macronizer.py#L68-L84
230,436
cltk/cltk
cltk/prosody/latin/macronizer.py
Macronizer._macronize_word
def _macronize_word(self, word): """Return macronized word. :param word: (word, tag) :ptype word: tuple :return: (word, tag, macronized_form) :rtype : tuple """ head_word = word[0] tag = word[1] if tag is None: logger.info('Tagger {} could not tag {}.'.format(self.tagger, head_word)) return head_word, tag, head_word elif tag == 'U--------': return (head_word, tag.lower(), head_word) else: entries = self._retrieve_morpheus_entry(head_word) if entries is None: return head_word, tag.lower(), head_word matched_entry = [entry for entry in entries if entry[0] == tag.lower()] if len(matched_entry) == 0: logger.info('No matching Morpheus entry found for {}.'.format(head_word)) return head_word, tag.lower(), entries[0][2] elif len(matched_entry) == 1: return head_word, tag.lower(), matched_entry[0][2].lower() else: logger.info('Multiple matching entries found for {}.'.format(head_word)) return head_word, tag.lower(), matched_entry[1][2].lower()
python
def _macronize_word(self, word): head_word = word[0] tag = word[1] if tag is None: logger.info('Tagger {} could not tag {}.'.format(self.tagger, head_word)) return head_word, tag, head_word elif tag == 'U--------': return (head_word, tag.lower(), head_word) else: entries = self._retrieve_morpheus_entry(head_word) if entries is None: return head_word, tag.lower(), head_word matched_entry = [entry for entry in entries if entry[0] == tag.lower()] if len(matched_entry) == 0: logger.info('No matching Morpheus entry found for {}.'.format(head_word)) return head_word, tag.lower(), entries[0][2] elif len(matched_entry) == 1: return head_word, tag.lower(), matched_entry[0][2].lower() else: logger.info('Multiple matching entries found for {}.'.format(head_word)) return head_word, tag.lower(), matched_entry[1][2].lower()
[ "def", "_macronize_word", "(", "self", ",", "word", ")", ":", "head_word", "=", "word", "[", "0", "]", "tag", "=", "word", "[", "1", "]", "if", "tag", "is", "None", ":", "logger", ".", "info", "(", "'Tagger {} could not tag {}.'", ".", "format", "(", ...
Return macronized word. :param word: (word, tag) :ptype word: tuple :return: (word, tag, macronized_form) :rtype : tuple
[ "Return", "macronized", "word", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/macronizer.py#L86-L113
230,437
cltk/cltk
cltk/prosody/latin/macronizer.py
Macronizer.macronize_tags
def macronize_tags(self, text): """Return macronized form along with POS tags. E.g. "Gallia est omnis divisa in partes tres," -> [('gallia', 'n-s---fb-', 'galliā'), ('est', 'v3spia---', 'est'), ('omnis', 'a-s---mn-', 'omnis'), ('divisa', 't-prppnn-', 'dīvīsa'), ('in', 'r--------', 'in'), ('partes', 'n-p---fa-', 'partēs'), ('tres', 'm--------', 'trēs')] :param text: raw text :return: tuples of head word, tag, macronized form :rtype : list """ return [self._macronize_word(word) for word in self._retrieve_tag(text)]
python
def macronize_tags(self, text): return [self._macronize_word(word) for word in self._retrieve_tag(text)]
[ "def", "macronize_tags", "(", "self", ",", "text", ")", ":", "return", "[", "self", ".", "_macronize_word", "(", "word", ")", "for", "word", "in", "self", ".", "_retrieve_tag", "(", "text", ")", "]" ]
Return macronized form along with POS tags. E.g. "Gallia est omnis divisa in partes tres," -> [('gallia', 'n-s---fb-', 'galliā'), ('est', 'v3spia---', 'est'), ('omnis', 'a-s---mn-', 'omnis'), ('divisa', 't-prppnn-', 'dīvīsa'), ('in', 'r--------', 'in'), ('partes', 'n-p---fa-', 'partēs'), ('tres', 'm--------', 'trēs')] :param text: raw text :return: tuples of head word, tag, macronized form :rtype : list
[ "Return", "macronized", "form", "along", "with", "POS", "tags", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/macronizer.py#L115-L127
230,438
cltk/cltk
cltk/prosody/latin/macronizer.py
Macronizer.macronize_text
def macronize_text(self, text): """Return macronized form of text. E.g. "Gallia est omnis divisa in partes tres," -> "galliā est omnis dīvīsa in partēs trēs ," :param text: raw text :return: macronized text :rtype : str """ macronized_words = [entry[2] for entry in self.macronize_tags(text)] return " ".join(macronized_words)
python
def macronize_text(self, text): macronized_words = [entry[2] for entry in self.macronize_tags(text)] return " ".join(macronized_words)
[ "def", "macronize_text", "(", "self", ",", "text", ")", ":", "macronized_words", "=", "[", "entry", "[", "2", "]", "for", "entry", "in", "self", ".", "macronize_tags", "(", "text", ")", "]", "return", "\" \"", ".", "join", "(", "macronized_words", ")" ]
Return macronized form of text. E.g. "Gallia est omnis divisa in partes tres," -> "galliā est omnis dīvīsa in partēs trēs ," :param text: raw text :return: macronized text :rtype : str
[ "Return", "macronized", "form", "of", "text", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/macronizer.py#L129-L140
230,439
cltk/cltk
cltk/corpus/akkadian/tokenizer.py
Tokenizer.string_tokenizer
def string_tokenizer(self, untokenized_string: str, include_blanks=False): """ This function is based off CLTK's line tokenizer. Use this for strings rather than .txt files. input: '20. u2-sza-bi-la-kum\n1. a-na ia-as2-ma-ah-{d}iszkur#\n2. qi2-bi2-ma\n3. um-ma {d}utu-szi-{d}iszkur\n' output:['20. u2-sza-bi-la-kum', '1. a-na ia-as2-ma-ah-{d}iszkur#', '2. qi2-bi2-ma'] :param untokenized_string: string :param include_blanks: instances of empty lines :return: lines as strings in list """ line_output = [] assert isinstance(untokenized_string, str), \ 'Incoming argument must be a string.' if include_blanks: tokenized_lines = untokenized_string.splitlines() else: tokenized_lines = [line for line in untokenized_string.splitlines() if line != r'\\n'] for line in tokenized_lines: # Strip out damage characters if not self.damage: # Add 'xn' -- missing sign or number? line = ''.join(c for c in line if c not in "#[]?!*") re.match(r'^\d*\.|\d\'\.', line) line_output.append(line.rstrip()) return line_output
python
def string_tokenizer(self, untokenized_string: str, include_blanks=False): line_output = [] assert isinstance(untokenized_string, str), \ 'Incoming argument must be a string.' if include_blanks: tokenized_lines = untokenized_string.splitlines() else: tokenized_lines = [line for line in untokenized_string.splitlines() if line != r'\\n'] for line in tokenized_lines: # Strip out damage characters if not self.damage: # Add 'xn' -- missing sign or number? line = ''.join(c for c in line if c not in "#[]?!*") re.match(r'^\d*\.|\d\'\.', line) line_output.append(line.rstrip()) return line_output
[ "def", "string_tokenizer", "(", "self", ",", "untokenized_string", ":", "str", ",", "include_blanks", "=", "False", ")", ":", "line_output", "=", "[", "]", "assert", "isinstance", "(", "untokenized_string", ",", "str", ")", ",", "'Incoming argument must be a strin...
This function is based off CLTK's line tokenizer. Use this for strings rather than .txt files. input: '20. u2-sza-bi-la-kum\n1. a-na ia-as2-ma-ah-{d}iszkur#\n2. qi2-bi2-ma\n3. um-ma {d}utu-szi-{d}iszkur\n' output:['20. u2-sza-bi-la-kum', '1. a-na ia-as2-ma-ah-{d}iszkur#', '2. qi2-bi2-ma'] :param untokenized_string: string :param include_blanks: instances of empty lines :return: lines as strings in list
[ "This", "function", "is", "based", "off", "CLTK", "s", "line", "tokenizer", ".", "Use", "this", "for", "strings", "rather", "than", ".", "txt", "files", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/akkadian/tokenizer.py#L49-L77
230,440
cltk/cltk
cltk/corpus/akkadian/tokenizer.py
Tokenizer.line_tokenizer
def line_tokenizer(self, text): """ From a .txt file, outputs lines as string in list. input: 21. u2-wa-a-ru at-ta e2-kal2-la-ka _e2_-ka wu-e-er 22. ... u2-ul szi-... 23. ... x ... output:['21. u2-wa-a-ru at-ta e2-kal2-la-ka _e2_-ka wu-e-er', '22. ... u2-ul szi-...', '23. ... x ...',] :param: .txt file containing untokenized string :return: lines as strings in list """ line_output = [] with open(text, mode='r+', encoding='utf8') as file: lines = file.readlines() assert isinstance(text, str), 'Incoming argument must be a string.' for line in lines: # Strip out damage characters if not self.damage: # Add 'xn' -- missing sign or number? line = ''.join(c for c in line if c not in "#[]?!*") re.match(r'^\d*\.|\d\'\.', line) line_output.append(line.rstrip()) return line_output
python
def line_tokenizer(self, text): line_output = [] with open(text, mode='r+', encoding='utf8') as file: lines = file.readlines() assert isinstance(text, str), 'Incoming argument must be a string.' for line in lines: # Strip out damage characters if not self.damage: # Add 'xn' -- missing sign or number? line = ''.join(c for c in line if c not in "#[]?!*") re.match(r'^\d*\.|\d\'\.', line) line_output.append(line.rstrip()) return line_output
[ "def", "line_tokenizer", "(", "self", ",", "text", ")", ":", "line_output", "=", "[", "]", "with", "open", "(", "text", ",", "mode", "=", "'r+'", ",", "encoding", "=", "'utf8'", ")", "as", "file", ":", "lines", "=", "file", ".", "readlines", "(", "...
From a .txt file, outputs lines as string in list. input: 21. u2-wa-a-ru at-ta e2-kal2-la-ka _e2_-ka wu-e-er 22. ... u2-ul szi-... 23. ... x ... output:['21. u2-wa-a-ru at-ta e2-kal2-la-ka _e2_-ka wu-e-er', '22. ... u2-ul szi-...', '23. ... x ...',] :param: .txt file containing untokenized string :return: lines as strings in list
[ "From", "a", ".", "txt", "file", "outputs", "lines", "as", "string", "in", "list", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/akkadian/tokenizer.py#L79-L104
230,441
cltk/cltk
cltk/stem/sanskrit/indian_syllabifier.py
Syllabifier.get_lang_data
def get_lang_data(self): """Define and call data for future use. Initializes and defines all variables which define the phonetic vectors. """ root = os.path.expanduser('~') csv_dir_path = os.path.join(root, 'cltk_data/sanskrit/model/sanskrit_models_cltk/phonetics') all_phonetic_csv = os.path.join(csv_dir_path, 'all_script_phonetic_data.csv') tamil_csv = os.path.join(csv_dir_path, 'tamil_script_phonetic_data.csv') # Make helper function for this with open(all_phonetic_csv,'r') as f: reader = csv.reader(f, delimiter = ',', quotechar = '"') next(reader, None) # Skip headers all_phonetic_data = [row for row in reader] with open(tamil_csv,'r') as f: reader = csv.reader(f, delimiter = ',', quotechar = '"') next(reader, None) # Skip headers # tamil_phonetic_data = [row[PHONETIC_VECTOR_START_OFFSET:] for row in reader] tamil_phonetic_data = [row for row in reader] # Handle better? all_phonetic_data = [[int(cell) if cell=='0' or cell=='1' else cell for cell in row] for row in all_phonetic_data] tamil_phonetic_data = [[int(cell) if cell=='0' or cell=='1' else cell for cell in row] for row in tamil_phonetic_data] all_phonetic_vectors = np.array([row[PHONETIC_VECTOR_START_OFFSET:] for row in all_phonetic_data]) tamil_phonetic_vectors = np.array([row[PHONETIC_VECTOR_START_OFFSET:] for row in tamil_phonetic_data]) phonetic_vector_length = all_phonetic_vectors.shape[1] return all_phonetic_data, tamil_phonetic_data, all_phonetic_vectors, tamil_phonetic_vectors, phonetic_vector_length
python
def get_lang_data(self): root = os.path.expanduser('~') csv_dir_path = os.path.join(root, 'cltk_data/sanskrit/model/sanskrit_models_cltk/phonetics') all_phonetic_csv = os.path.join(csv_dir_path, 'all_script_phonetic_data.csv') tamil_csv = os.path.join(csv_dir_path, 'tamil_script_phonetic_data.csv') # Make helper function for this with open(all_phonetic_csv,'r') as f: reader = csv.reader(f, delimiter = ',', quotechar = '"') next(reader, None) # Skip headers all_phonetic_data = [row for row in reader] with open(tamil_csv,'r') as f: reader = csv.reader(f, delimiter = ',', quotechar = '"') next(reader, None) # Skip headers # tamil_phonetic_data = [row[PHONETIC_VECTOR_START_OFFSET:] for row in reader] tamil_phonetic_data = [row for row in reader] # Handle better? all_phonetic_data = [[int(cell) if cell=='0' or cell=='1' else cell for cell in row] for row in all_phonetic_data] tamil_phonetic_data = [[int(cell) if cell=='0' or cell=='1' else cell for cell in row] for row in tamil_phonetic_data] all_phonetic_vectors = np.array([row[PHONETIC_VECTOR_START_OFFSET:] for row in all_phonetic_data]) tamil_phonetic_vectors = np.array([row[PHONETIC_VECTOR_START_OFFSET:] for row in tamil_phonetic_data]) phonetic_vector_length = all_phonetic_vectors.shape[1] return all_phonetic_data, tamil_phonetic_data, all_phonetic_vectors, tamil_phonetic_vectors, phonetic_vector_length
[ "def", "get_lang_data", "(", "self", ")", ":", "root", "=", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", "csv_dir_path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "'cltk_data/sanskrit/model/sanskrit_models_cltk/phonetics'", ")", "all_pho...
Define and call data for future use. Initializes and defines all variables which define the phonetic vectors.
[ "Define", "and", "call", "data", "for", "future", "use", ".", "Initializes", "and", "defines", "all", "variables", "which", "define", "the", "phonetic", "vectors", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/stem/sanskrit/indian_syllabifier.py#L87-L119
230,442
cltk/cltk
cltk/stem/sanskrit/indian_syllabifier.py
Syllabifier.orthographic_syllabify
def orthographic_syllabify(self, word): """Main syllablic function.""" p_vectors = [self.get_phonetic_feature_vector(c, self.lang) for c in word] syllables = [] for i in range(len(word)): v = p_vectors[i] syllables.append(word[i]) if i + 1 < len(word) and (not self.is_valid(p_vectors[i + 1]) or self.is_misc(p_vectors[i + 1])): syllables.append(u' ') elif not self.is_valid(v) or self.is_misc(v): syllables.append(u' ') elif self.is_vowel(v): anu_nonplos = (i + 2 < len(word) and self.is_anusvaar(p_vectors[i + 1]) and not self.is_plosive(p_vectors[i + 2]) ) anu_eow = (i + 2 == len(word) and self.is_anusvaar(p_vectors[i + 1])) if not (anu_nonplos or anu_eow): syllables.append(u' ') elif i + 1 < len(word) and (self.is_consonant(v) or self.is_nukta(v)): if self.is_consonant(p_vectors[i + 1]): syllables.append(u' ') elif self.is_vowel(p_vectors[i + 1]) and not self.is_dependent_vowel(p_vectors[i + 1]): syllables.append(u' ') elif self.is_anusvaar(p_vectors[i + 1]): anu_nonplos = (i + 2 < len(word) and not self.is_plosive(p_vectors[i + 2])) anu_eow = i + 2 == len(word) if not (anu_nonplos or anu_eow): syllables.append(u' ') return u''.join(syllables).strip().split(u' ')
python
def orthographic_syllabify(self, word): p_vectors = [self.get_phonetic_feature_vector(c, self.lang) for c in word] syllables = [] for i in range(len(word)): v = p_vectors[i] syllables.append(word[i]) if i + 1 < len(word) and (not self.is_valid(p_vectors[i + 1]) or self.is_misc(p_vectors[i + 1])): syllables.append(u' ') elif not self.is_valid(v) or self.is_misc(v): syllables.append(u' ') elif self.is_vowel(v): anu_nonplos = (i + 2 < len(word) and self.is_anusvaar(p_vectors[i + 1]) and not self.is_plosive(p_vectors[i + 2]) ) anu_eow = (i + 2 == len(word) and self.is_anusvaar(p_vectors[i + 1])) if not (anu_nonplos or anu_eow): syllables.append(u' ') elif i + 1 < len(word) and (self.is_consonant(v) or self.is_nukta(v)): if self.is_consonant(p_vectors[i + 1]): syllables.append(u' ') elif self.is_vowel(p_vectors[i + 1]) and not self.is_dependent_vowel(p_vectors[i + 1]): syllables.append(u' ') elif self.is_anusvaar(p_vectors[i + 1]): anu_nonplos = (i + 2 < len(word) and not self.is_plosive(p_vectors[i + 2])) anu_eow = i + 2 == len(word) if not (anu_nonplos or anu_eow): syllables.append(u' ') return u''.join(syllables).strip().split(u' ')
[ "def", "orthographic_syllabify", "(", "self", ",", "word", ")", ":", "p_vectors", "=", "[", "self", ".", "get_phonetic_feature_vector", "(", "c", ",", "self", ".", "lang", ")", "for", "c", "in", "word", "]", "syllables", "=", "[", "]", "for", "i", "in"...
Main syllablic function.
[ "Main", "syllablic", "function", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/stem/sanskrit/indian_syllabifier.py#L217-L260
230,443
cltk/cltk
cltk/utils/philology.py
read_file
def read_file(filepath: str) -> str: """Read a file and return it as a string""" # ? Check this is ok if absolute paths passed in filepath = os.path.expanduser(filepath) with open(filepath) as opened_file: # type: IO file_read = opened_file.read() # type: str return file_read
python
def read_file(filepath: str) -> str: # ? Check this is ok if absolute paths passed in filepath = os.path.expanduser(filepath) with open(filepath) as opened_file: # type: IO file_read = opened_file.read() # type: str return file_read
[ "def", "read_file", "(", "filepath", ":", "str", ")", "->", "str", ":", "# ? Check this is ok if absolute paths passed in", "filepath", "=", "os", ".", "path", ".", "expanduser", "(", "filepath", ")", "with", "open", "(", "filepath", ")", "as", "opened_file", ...
Read a file and return it as a string
[ "Read", "a", "file", "and", "return", "it", "as", "a", "string" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/utils/philology.py#L25-L31
230,444
cltk/cltk
cltk/utils/philology.py
ConcordanceIndex.return_concordance_all
def return_concordance_all(self, tokens: List[str]) -> List[List[str]]: """Take a list of tokens, iteratively run each word through return_concordance_word and build a list of all. This returns a list of lists. """ coll = pyuca.Collator() # type: pyuca.Collator tokens = sorted(tokens, key=coll.sort_key) #! is the list order preserved? concordance_list = [] # type: List[List[str]] for token in tokens: concordance_list_for_word = self.return_concordance_word(token) # List[str] if concordance_list_for_word: concordance_list.append(concordance_list_for_word) return concordance_list
python
def return_concordance_all(self, tokens: List[str]) -> List[List[str]]: coll = pyuca.Collator() # type: pyuca.Collator tokens = sorted(tokens, key=coll.sort_key) #! is the list order preserved? concordance_list = [] # type: List[List[str]] for token in tokens: concordance_list_for_word = self.return_concordance_word(token) # List[str] if concordance_list_for_word: concordance_list.append(concordance_list_for_word) return concordance_list
[ "def", "return_concordance_all", "(", "self", ",", "tokens", ":", "List", "[", "str", "]", ")", "->", "List", "[", "List", "[", "str", "]", "]", ":", "coll", "=", "pyuca", ".", "Collator", "(", ")", "# type: pyuca.Collator", "tokens", "=", "sorted", "(...
Take a list of tokens, iteratively run each word through return_concordance_word and build a list of all. This returns a list of lists.
[ "Take", "a", "list", "of", "tokens", "iteratively", "run", "each", "word", "through", "return_concordance_word", "and", "build", "a", "list", "of", "all", ".", "This", "returns", "a", "list", "of", "lists", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/utils/philology.py#L196-L211
230,445
cltk/cltk
cltk/prosody/latin/scansion_formatter.py
ScansionFormatter.hexameter
def hexameter(self, line: str) -> str: """ Format a string of hexameter metrical stress patterns into foot divisions :param line: the scansion pattern :return: the scansion string formatted with foot breaks >>> print(ScansionFormatter().hexameter( "-UU-UU-UU---UU--")) -UU|-UU|-UU|--|-UU|-- """ mylist = list(line) items = len(mylist) idx_start = items - 2 idx_end = items while idx_start > 0: potential_foot = "".join(mylist[idx_start: idx_end]) if potential_foot == self.constants.HEXAMETER_ENDING or \ potential_foot == self.constants.SPONDEE: mylist.insert(idx_start, self.constants.FOOT_SEPARATOR) idx_start -= 1 idx_end -= 2 if potential_foot == self.constants.DACTYL: mylist.insert(idx_start, "|") idx_start -= 1 idx_end -= 3 idx_start -= 1 return "".join(mylist)
python
def hexameter(self, line: str) -> str: mylist = list(line) items = len(mylist) idx_start = items - 2 idx_end = items while idx_start > 0: potential_foot = "".join(mylist[idx_start: idx_end]) if potential_foot == self.constants.HEXAMETER_ENDING or \ potential_foot == self.constants.SPONDEE: mylist.insert(idx_start, self.constants.FOOT_SEPARATOR) idx_start -= 1 idx_end -= 2 if potential_foot == self.constants.DACTYL: mylist.insert(idx_start, "|") idx_start -= 1 idx_end -= 3 idx_start -= 1 return "".join(mylist)
[ "def", "hexameter", "(", "self", ",", "line", ":", "str", ")", "->", "str", ":", "mylist", "=", "list", "(", "line", ")", "items", "=", "len", "(", "mylist", ")", "idx_start", "=", "items", "-", "2", "idx_end", "=", "items", "while", "idx_start", "...
Format a string of hexameter metrical stress patterns into foot divisions :param line: the scansion pattern :return: the scansion string formatted with foot breaks >>> print(ScansionFormatter().hexameter( "-UU-UU-UU---UU--")) -UU|-UU|-UU|--|-UU|--
[ "Format", "a", "string", "of", "hexameter", "metrical", "stress", "patterns", "into", "foot", "divisions" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/scansion_formatter.py#L33-L59
230,446
cltk/cltk
cltk/prosody/latin/scansion_formatter.py
ScansionFormatter.merge_line_scansion
def merge_line_scansion(self, line: str, scansion: str) -> str: """ Merge a line of verse with its scansion string. Do not accent dipthongs. :param line: the original Latin verse line :param scansion: the scansion pattern :return: the original line with the scansion pattern applied via macrons >>> print(ScansionFormatter().merge_line_scansion( ... "Arma virumque cano, Troiae qui prīmus ab ōrīs", ... "- U U - U U - UU- - - U U - -")) Ārma virūmque canō, Troiae quī prīmus ab ōrīs >>> print(ScansionFormatter().merge_line_scansion( ... "lītora, multum ille et terrīs iactātus et alto", ... " - U U - - - - - - - U U - U")) lītora, mūltum īlle ēt tērrīs iāctātus et ālto >>> print(ScansionFormatter().merge_line_scansion( ... 'aut facere, haec a te dictaque factaque sunt', ... ' - U U - - - - U U - U U - ')) aut facere, haec ā tē dīctaque fāctaque sūnt """ letters = list(line) marks = list(scansion) if len(scansion) < len(line): marks += ((len(line) - len(scansion)) * " ").split() for idx in range(0, len(marks)): if marks[idx] == self.constants.STRESSED: vowel = letters[idx] if vowel not in self.stress_accent_dict: LOG.error("problem! vowel: {} not in dict for line {}".format(vowel, line)) pass else: if idx > 1: if (letters[idx -2] + letters[idx - 1]).lower() == "qu": new_vowel = self.stress_accent_dict[vowel] letters[idx] = new_vowel continue if idx > 0: if letters[idx - 1] + vowel in self.constants.DIPTHONGS: continue new_vowel = self.stress_accent_dict[vowel] letters[idx] = new_vowel else: new_vowel = self.stress_accent_dict[vowel] letters[idx] = new_vowel return "".join(letters).rstrip()
python
def merge_line_scansion(self, line: str, scansion: str) -> str: letters = list(line) marks = list(scansion) if len(scansion) < len(line): marks += ((len(line) - len(scansion)) * " ").split() for idx in range(0, len(marks)): if marks[idx] == self.constants.STRESSED: vowel = letters[idx] if vowel not in self.stress_accent_dict: LOG.error("problem! vowel: {} not in dict for line {}".format(vowel, line)) pass else: if idx > 1: if (letters[idx -2] + letters[idx - 1]).lower() == "qu": new_vowel = self.stress_accent_dict[vowel] letters[idx] = new_vowel continue if idx > 0: if letters[idx - 1] + vowel in self.constants.DIPTHONGS: continue new_vowel = self.stress_accent_dict[vowel] letters[idx] = new_vowel else: new_vowel = self.stress_accent_dict[vowel] letters[idx] = new_vowel return "".join(letters).rstrip()
[ "def", "merge_line_scansion", "(", "self", ",", "line", ":", "str", ",", "scansion", ":", "str", ")", "->", "str", ":", "letters", "=", "list", "(", "line", ")", "marks", "=", "list", "(", "scansion", ")", "if", "len", "(", "scansion", ")", "<", "l...
Merge a line of verse with its scansion string. Do not accent dipthongs. :param line: the original Latin verse line :param scansion: the scansion pattern :return: the original line with the scansion pattern applied via macrons >>> print(ScansionFormatter().merge_line_scansion( ... "Arma virumque cano, Troiae qui prīmus ab ōrīs", ... "- U U - U U - UU- - - U U - -")) Ārma virūmque canō, Troiae quī prīmus ab ōrīs >>> print(ScansionFormatter().merge_line_scansion( ... "lītora, multum ille et terrīs iactātus et alto", ... " - U U - - - - - - - U U - U")) lītora, mūltum īlle ēt tērrīs iāctātus et ālto >>> print(ScansionFormatter().merge_line_scansion( ... 'aut facere, haec a te dictaque factaque sunt', ... ' - U U - - - - U U - U U - ')) aut facere, haec ā tē dīctaque fāctaque sūnt
[ "Merge", "a", "line", "of", "verse", "with", "its", "scansion", "string", ".", "Do", "not", "accent", "dipthongs", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/scansion_formatter.py#L61-L108
230,447
cltk/cltk
cltk/corpus/arabic/utils/pyarabic/araby.py
arabicrange
def arabicrange(): u"""return a list of arabic characteres . Return a list of characteres between \u060c to \u0652 @return: list of arabic characteres. @rtype: unicode """ mylist = [] for i in range(0x0600, 0x00653): try: mylist.append(unichr(i)) except NameError: # python 3 compatible mylist.append(chr(i)) except ValueError: pass return mylist
python
def arabicrange(): u"""return a list of arabic characteres . Return a list of characteres between \u060c to \u0652 @return: list of arabic characteres. @rtype: unicode """ mylist = [] for i in range(0x0600, 0x00653): try: mylist.append(unichr(i)) except NameError: # python 3 compatible mylist.append(chr(i)) except ValueError: pass return mylist
[ "def", "arabicrange", "(", ")", ":", "mylist", "=", "[", "]", "for", "i", "in", "range", "(", "0x0600", ",", "0x00653", ")", ":", "try", ":", "mylist", ".", "append", "(", "unichr", "(", "i", ")", ")", "except", "NameError", ":", "# python 3 compatib...
u"""return a list of arabic characteres . Return a list of characteres between \u060c to \u0652 @return: list of arabic characteres. @rtype: unicode
[ "u", "return", "a", "list", "of", "arabic", "characteres", ".", "Return", "a", "list", "of", "characteres", "between", "\\", "u060c", "to", "\\", "u0652" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/arabic/utils/pyarabic/araby.py#L482-L497
230,448
cltk/cltk
cltk/corpus/arabic/utils/pyarabic/araby.py
is_vocalized
def is_vocalized(word): """Checks if the arabic word is vocalized. the word musn't have any spaces and pounctuations. @param word: arabic unicode char @type word: unicode @return: if the word is vocalized @rtype:Boolean """ if word.isalpha(): return False for char in word: if is_tashkeel(char): return True else: return False
python
def is_vocalized(word): if word.isalpha(): return False for char in word: if is_tashkeel(char): return True else: return False
[ "def", "is_vocalized", "(", "word", ")", ":", "if", "word", ".", "isalpha", "(", ")", ":", "return", "False", "for", "char", "in", "word", ":", "if", "is_tashkeel", "(", "char", ")", ":", "return", "True", "else", ":", "return", "False" ]
Checks if the arabic word is vocalized. the word musn't have any spaces and pounctuations. @param word: arabic unicode char @type word: unicode @return: if the word is vocalized @rtype:Boolean
[ "Checks", "if", "the", "arabic", "word", "is", "vocalized", ".", "the", "word", "musn", "t", "have", "any", "spaces", "and", "pounctuations", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/arabic/utils/pyarabic/araby.py#L518-L532
230,449
cltk/cltk
cltk/corpus/arabic/utils/pyarabic/araby.py
is_arabicstring
def is_arabicstring(text): """ Checks for an Arabic standard Unicode block characters An arabic string can contain spaces, digits and pounctuation. but only arabic standard characters, not extended arabic @param text: input text @type text: unicode @return: True if all charaters are in Arabic block @rtype: Boolean """ if re.search(u"([^\u0600-\u0652%s%s%s\s\d])" \ % (LAM_ALEF, LAM_ALEF_HAMZA_ABOVE, LAM_ALEF_MADDA_ABOVE), text): return False return True
python
def is_arabicstring(text): if re.search(u"([^\u0600-\u0652%s%s%s\s\d])" \ % (LAM_ALEF, LAM_ALEF_HAMZA_ABOVE, LAM_ALEF_MADDA_ABOVE), text): return False return True
[ "def", "is_arabicstring", "(", "text", ")", ":", "if", "re", ".", "search", "(", "u\"([^\\u0600-\\u0652%s%s%s\\s\\d])\"", "%", "(", "LAM_ALEF", ",", "LAM_ALEF_HAMZA_ABOVE", ",", "LAM_ALEF_MADDA_ABOVE", ")", ",", "text", ")", ":", "return", "False", "return", "Tr...
Checks for an Arabic standard Unicode block characters An arabic string can contain spaces, digits and pounctuation. but only arabic standard characters, not extended arabic @param text: input text @type text: unicode @return: True if all charaters are in Arabic block @rtype: Boolean
[ "Checks", "for", "an", "Arabic", "standard", "Unicode", "block", "characters", "An", "arabic", "string", "can", "contain", "spaces", "digits", "and", "pounctuation", ".", "but", "only", "arabic", "standard", "characters", "not", "extended", "arabic" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/arabic/utils/pyarabic/araby.py#L549-L561
230,450
cltk/cltk
cltk/corpus/arabic/utils/pyarabic/araby.py
is_arabicword
def is_arabicword(word): """ Checks for an valid Arabic word. An Arabic word not contains spaces, digits and pounctuation avoid some spelling error, TEH_MARBUTA must be at the end. @param word: input word @type word: unicode @return: True if all charaters are in Arabic block @rtype: Boolean """ if len(word) == 0: return False elif re.search(u"([^\u0600-\u0652%s%s%s])" \ % (LAM_ALEF, LAM_ALEF_HAMZA_ABOVE, LAM_ALEF_MADDA_ABOVE), word): return False elif is_haraka(word[0]) or word[0] in (WAW_HAMZA, YEH_HAMZA): return False # if Teh Marbuta or Alef_Maksura not in the end elif re.match(u"^(.)*[%s](.)+$" % ALEF_MAKSURA, word): return False elif re.match(u"^(.)*[%s]([^%s%s%s])(.)+$" % \ (TEH_MARBUTA, DAMMA, KASRA, FATHA), word): return False else: return True
python
def is_arabicword(word): if len(word) == 0: return False elif re.search(u"([^\u0600-\u0652%s%s%s])" \ % (LAM_ALEF, LAM_ALEF_HAMZA_ABOVE, LAM_ALEF_MADDA_ABOVE), word): return False elif is_haraka(word[0]) or word[0] in (WAW_HAMZA, YEH_HAMZA): return False # if Teh Marbuta or Alef_Maksura not in the end elif re.match(u"^(.)*[%s](.)+$" % ALEF_MAKSURA, word): return False elif re.match(u"^(.)*[%s]([^%s%s%s])(.)+$" % \ (TEH_MARBUTA, DAMMA, KASRA, FATHA), word): return False else: return True
[ "def", "is_arabicword", "(", "word", ")", ":", "if", "len", "(", "word", ")", "==", "0", ":", "return", "False", "elif", "re", ".", "search", "(", "u\"([^\\u0600-\\u0652%s%s%s])\"", "%", "(", "LAM_ALEF", ",", "LAM_ALEF_HAMZA_ABOVE", ",", "LAM_ALEF_MADDA_ABOVE"...
Checks for an valid Arabic word. An Arabic word not contains spaces, digits and pounctuation avoid some spelling error, TEH_MARBUTA must be at the end. @param word: input word @type word: unicode @return: True if all charaters are in Arabic block @rtype: Boolean
[ "Checks", "for", "an", "valid", "Arabic", "word", ".", "An", "Arabic", "word", "not", "contains", "spaces", "digits", "and", "pounctuation", "avoid", "some", "spelling", "error", "TEH_MARBUTA", "must", "be", "at", "the", "end", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/arabic/utils/pyarabic/araby.py#L577-L600
230,451
cltk/cltk
cltk/corpus/arabic/utils/pyarabic/araby.py
normalize_hamza
def normalize_hamza(word): """Standardize the Hamzat into one form of hamza, replace Madda by hamza and alef. Replace the LamAlefs by simplified letters. @param word: arabic text. @type word: unicode. @return: return a converted text. @rtype: unicode. """ if word.startswith(ALEF_MADDA): if len(word) >= 3 and (word[1] not in HARAKAT) and \ (word[2] == SHADDA or len(word) == 3): word = HAMZA + ALEF + word[1:] else: word = HAMZA + HAMZA + word[1:] # convert all Hamza from into one form word = word.replace(ALEF_MADDA, HAMZA + HAMZA) word = HAMZAT_PATTERN.sub(HAMZA, word) return word
python
def normalize_hamza(word): if word.startswith(ALEF_MADDA): if len(word) >= 3 and (word[1] not in HARAKAT) and \ (word[2] == SHADDA or len(word) == 3): word = HAMZA + ALEF + word[1:] else: word = HAMZA + HAMZA + word[1:] # convert all Hamza from into one form word = word.replace(ALEF_MADDA, HAMZA + HAMZA) word = HAMZAT_PATTERN.sub(HAMZA, word) return word
[ "def", "normalize_hamza", "(", "word", ")", ":", "if", "word", ".", "startswith", "(", "ALEF_MADDA", ")", ":", "if", "len", "(", "word", ")", ">=", "3", "and", "(", "word", "[", "1", "]", "not", "in", "HARAKAT", ")", "and", "(", "word", "[", "2",...
Standardize the Hamzat into one form of hamza, replace Madda by hamza and alef. Replace the LamAlefs by simplified letters. @param word: arabic text. @type word: unicode. @return: return a converted text. @rtype: unicode.
[ "Standardize", "the", "Hamzat", "into", "one", "form", "of", "hamza", "replace", "Madda", "by", "hamza", "and", "alef", ".", "Replace", "the", "LamAlefs", "by", "simplified", "letters", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/arabic/utils/pyarabic/araby.py#L760-L779
230,452
cltk/cltk
cltk/corpus/arabic/utils/pyarabic/araby.py
joint
def joint(letters, marks): """ joint the letters with the marks the length ot letters and marks must be equal return word @param letters: the word letters @type letters: unicode @param marks: the word marks @type marks: unicode @return: word @rtype: unicode """ # The length ot letters and marks must be equal if len(letters) != len(marks): return "" stack_letter = stack.Stack(letters) stack_letter.items.reverse() stack_mark = stack.Stack(marks) stack_mark.items.reverse() word_stack = stack.Stack() last_letter = stack_letter.pop() last_mark = stack_mark.pop() vowels = HARAKAT while last_letter != None and last_mark != None: if last_letter == SHADDA: top = word_stack.pop() if top not in vowels: word_stack.push(top) word_stack.push(last_letter) if last_mark != NOT_DEF_HARAKA: word_stack.push(last_mark) else: word_stack.push(last_letter) if last_mark != NOT_DEF_HARAKA: word_stack.push(last_mark) last_letter = stack_letter.pop() last_mark = stack_mark.pop() if not (stack_letter.is_empty() and stack_mark.is_empty()): return False else: return ''.join(word_stack.items)
python
def joint(letters, marks): # The length ot letters and marks must be equal if len(letters) != len(marks): return "" stack_letter = stack.Stack(letters) stack_letter.items.reverse() stack_mark = stack.Stack(marks) stack_mark.items.reverse() word_stack = stack.Stack() last_letter = stack_letter.pop() last_mark = stack_mark.pop() vowels = HARAKAT while last_letter != None and last_mark != None: if last_letter == SHADDA: top = word_stack.pop() if top not in vowels: word_stack.push(top) word_stack.push(last_letter) if last_mark != NOT_DEF_HARAKA: word_stack.push(last_mark) else: word_stack.push(last_letter) if last_mark != NOT_DEF_HARAKA: word_stack.push(last_mark) last_letter = stack_letter.pop() last_mark = stack_mark.pop() if not (stack_letter.is_empty() and stack_mark.is_empty()): return False else: return ''.join(word_stack.items)
[ "def", "joint", "(", "letters", ",", "marks", ")", ":", "# The length ot letters and marks must be equal", "if", "len", "(", "letters", ")", "!=", "len", "(", "marks", ")", ":", "return", "\"\"", "stack_letter", "=", "stack", ".", "Stack", "(", "letters", ")...
joint the letters with the marks the length ot letters and marks must be equal return word @param letters: the word letters @type letters: unicode @param marks: the word marks @type marks: unicode @return: word @rtype: unicode
[ "joint", "the", "letters", "with", "the", "marks", "the", "length", "ot", "letters", "and", "marks", "must", "be", "equal", "return", "word" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/arabic/utils/pyarabic/araby.py#L838-L880
230,453
cltk/cltk
cltk/corpus/arabic/utils/pyarabic/araby.py
shaddalike
def shaddalike(partial, fully): """ If the two words has the same letters and the same harakats, this fuction return True. The first word is partially vocalized, the second is fully if the partially contians a shadda, it must be at the same place in the fully @param partial: the partially vocalized word @type partial: unicode @param fully: the fully vocalized word @type fully: unicode @return: if contains shadda @rtype: Boolean """ # المدخل ليس به شدة، لا داعي للبحث if not has_shadda(partial): return True # المدخل به شدة، والنتيجة ليس بها شدة، خاطئ elif not has_shadda(fully) and has_shadda(partial): return False # المدخل والمخرج بهما شدة، نتأكد من موقعهما partial = strip_harakat(partial) fully = strip_harakat(fully) pstack = stack.Stack(partial) vstack = stack.Stack(fully) plast = pstack.pop() vlast = vstack.pop() # if debug: print "+0", Pstack, Vstack while plast != None and vlast != None: if plast == vlast: plast = pstack.pop() vlast = vstack.pop() elif plast == SHADDA and vlast != SHADDA: # if debug: print "+2", Pstack.items, Plast, Vstack.items, Vlast break elif plast != SHADDA and vlast == SHADDA: # if debug: print "+2", Pstack.items, Plast, Vstack.items, Vlast vlast = vstack.pop() else: # if debug: print "+2", Pstack.items, Plast, Vstack.items, Vlast break if not (pstack.is_empty() and vstack.is_empty()): return False else: return True
python
def shaddalike(partial, fully): # المدخل ليس به شدة، لا داعي للبحث if not has_shadda(partial): return True # المدخل به شدة، والنتيجة ليس بها شدة، خاطئ elif not has_shadda(fully) and has_shadda(partial): return False # المدخل والمخرج بهما شدة، نتأكد من موقعهما partial = strip_harakat(partial) fully = strip_harakat(fully) pstack = stack.Stack(partial) vstack = stack.Stack(fully) plast = pstack.pop() vlast = vstack.pop() # if debug: print "+0", Pstack, Vstack while plast != None and vlast != None: if plast == vlast: plast = pstack.pop() vlast = vstack.pop() elif plast == SHADDA and vlast != SHADDA: # if debug: print "+2", Pstack.items, Plast, Vstack.items, Vlast break elif plast != SHADDA and vlast == SHADDA: # if debug: print "+2", Pstack.items, Plast, Vstack.items, Vlast vlast = vstack.pop() else: # if debug: print "+2", Pstack.items, Plast, Vstack.items, Vlast break if not (pstack.is_empty() and vstack.is_empty()): return False else: return True
[ "def", "shaddalike", "(", "partial", ",", "fully", ")", ":", "# المدخل ليس به شدة، لا داعي للبحث", "if", "not", "has_shadda", "(", "partial", ")", ":", "return", "True", "# المدخل به شدة، والنتيجة ليس بها شدة، خاطئ", "elif", "not", "has_shadda", "(", "fully", ")", "...
If the two words has the same letters and the same harakats, this fuction return True. The first word is partially vocalized, the second is fully if the partially contians a shadda, it must be at the same place in the fully @param partial: the partially vocalized word @type partial: unicode @param fully: the fully vocalized word @type fully: unicode @return: if contains shadda @rtype: Boolean
[ "If", "the", "two", "words", "has", "the", "same", "letters", "and", "the", "same", "harakats", "this", "fuction", "return", "True", ".", "The", "first", "word", "is", "partially", "vocalized", "the", "second", "is", "fully", "if", "the", "partially", "con...
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/arabic/utils/pyarabic/araby.py#L948-L992
230,454
cltk/cltk
cltk/corpus/arabic/utils/pyarabic/araby.py
reduce_tashkeel
def reduce_tashkeel(text): """Reduce the Tashkeel, by deleting evident cases. @param text: the input text fully vocalized. @type text: unicode. @return : partially vocalized text. @rtype: unicode. """ patterns = [ # delete all fathat, except on waw and yeh u"(?<!(%s|%s))(%s|%s)" % (WAW, YEH, SUKUN, FATHA), # delete damma if followed by waw. u"%s(?=%s)" % (DAMMA, WAW), # delete kasra if followed by yeh. u"%s(?=%s)" % (KASRA, YEH), # delete fatha if followed by alef to reduce yeh maftouha # and waw maftouha before alef. u"%s(?=%s)" % (FATHA, ALEF), # delete fatha from yeh and waw if they are in the word begining. u"(?<=\s(%s|%s))%s" % (WAW, YEH, FATHA), # delete kasra if preceded by Hamza below alef. u"(?<=%s)%s" % (ALEF_HAMZA_BELOW, KASRA), ] reduced = text for pat in patterns: reduced = re.sub(pat, '', reduced) return reduced
python
def reduce_tashkeel(text): patterns = [ # delete all fathat, except on waw and yeh u"(?<!(%s|%s))(%s|%s)" % (WAW, YEH, SUKUN, FATHA), # delete damma if followed by waw. u"%s(?=%s)" % (DAMMA, WAW), # delete kasra if followed by yeh. u"%s(?=%s)" % (KASRA, YEH), # delete fatha if followed by alef to reduce yeh maftouha # and waw maftouha before alef. u"%s(?=%s)" % (FATHA, ALEF), # delete fatha from yeh and waw if they are in the word begining. u"(?<=\s(%s|%s))%s" % (WAW, YEH, FATHA), # delete kasra if preceded by Hamza below alef. u"(?<=%s)%s" % (ALEF_HAMZA_BELOW, KASRA), ] reduced = text for pat in patterns: reduced = re.sub(pat, '', reduced) return reduced
[ "def", "reduce_tashkeel", "(", "text", ")", ":", "patterns", "=", "[", "# delete all fathat, except on waw and yeh", "u\"(?<!(%s|%s))(%s|%s)\"", "%", "(", "WAW", ",", "YEH", ",", "SUKUN", ",", "FATHA", ")", ",", "# delete damma if followed by waw.", "u\"%s(?=%s)\"", ...
Reduce the Tashkeel, by deleting evident cases. @param text: the input text fully vocalized. @type text: unicode. @return : partially vocalized text. @rtype: unicode.
[ "Reduce", "the", "Tashkeel", "by", "deleting", "evident", "cases", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/arabic/utils/pyarabic/araby.py#L995-L1022
230,455
cltk/cltk
cltk/corpus/arabic/utils/pyarabic/araby.py
vocalized_similarity
def vocalized_similarity(word1, word2): """ if the two words has the same letters and the same harakats, this function return True. The two words can be full vocalized, or partial vocalized @param word1: first word @type word1: unicode @param word2: second word @type word2: unicode @return: return if words are similar, else return negative number of errors @rtype: Boolean / int """ stack1 = stack.Stack(word1) stack2 = stack.Stack(word2) last1 = stack1.pop() last2 = stack2.pop() err_count = 0 vowels = HARAKAT while last1 != None and last2 != None: if last1 == last2: last1 = stack1.pop() last2 = stack2.pop() elif last1 in vowels and last2 not in vowels: last1 = stack1.pop() elif last1 not in vowels and last2 in vowels: last2 = stack2.pop() else: # break if last1 == SHADDA: last1 = stack1.pop() elif last2 == SHADDA: last2 = stack2.pop() else: last1 = stack1.pop() last2 = stack2.pop() err_count += 1 if err_count > 0: return -err_count else: return True
python
def vocalized_similarity(word1, word2): stack1 = stack.Stack(word1) stack2 = stack.Stack(word2) last1 = stack1.pop() last2 = stack2.pop() err_count = 0 vowels = HARAKAT while last1 != None and last2 != None: if last1 == last2: last1 = stack1.pop() last2 = stack2.pop() elif last1 in vowels and last2 not in vowels: last1 = stack1.pop() elif last1 not in vowels and last2 in vowels: last2 = stack2.pop() else: # break if last1 == SHADDA: last1 = stack1.pop() elif last2 == SHADDA: last2 = stack2.pop() else: last1 = stack1.pop() last2 = stack2.pop() err_count += 1 if err_count > 0: return -err_count else: return True
[ "def", "vocalized_similarity", "(", "word1", ",", "word2", ")", ":", "stack1", "=", "stack", ".", "Stack", "(", "word1", ")", "stack2", "=", "stack", ".", "Stack", "(", "word2", ")", "last1", "=", "stack1", ".", "pop", "(", ")", "last2", "=", "stack2...
if the two words has the same letters and the same harakats, this function return True. The two words can be full vocalized, or partial vocalized @param word1: first word @type word1: unicode @param word2: second word @type word2: unicode @return: return if words are similar, else return negative number of errors @rtype: Boolean / int
[ "if", "the", "two", "words", "has", "the", "same", "letters", "and", "the", "same", "harakats", "this", "function", "return", "True", ".", "The", "two", "words", "can", "be", "full", "vocalized", "or", "partial", "vocalized" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/arabic/utils/pyarabic/araby.py#L1025-L1065
230,456
cltk/cltk
cltk/corpus/arabic/utils/pyarabic/araby.py
tokenize
def tokenize(text=""): """ Tokenize text into words. @param text: the input text. @type text: unicode. @return: list of words. @rtype: list. """ if text == '': return [] else: # split tokens mylist = TOKEN_PATTERN.split(text) # don't remove newline \n mylist = [TOKEN_REPLACE.sub('', x) for x in mylist if x] # remove empty substring mylist = [x for x in mylist if x] return mylist
python
def tokenize(text=""): if text == '': return [] else: # split tokens mylist = TOKEN_PATTERN.split(text) # don't remove newline \n mylist = [TOKEN_REPLACE.sub('', x) for x in mylist if x] # remove empty substring mylist = [x for x in mylist if x] return mylist
[ "def", "tokenize", "(", "text", "=", "\"\"", ")", ":", "if", "text", "==", "''", ":", "return", "[", "]", "else", ":", "# split tokens", "mylist", "=", "TOKEN_PATTERN", ".", "split", "(", "text", ")", "# don't remove newline \\n", "mylist", "=", "[", "TO...
Tokenize text into words. @param text: the input text. @type text: unicode. @return: list of words. @rtype: list.
[ "Tokenize", "text", "into", "words", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/arabic/utils/pyarabic/araby.py#L1068-L1086
230,457
cltk/cltk
cltk/vector/word2vec.py
gen_docs
def gen_docs(corpus, lemmatize, rm_stops): """Open and process files from a corpus. Return a list of sentences for an author. Each sentence is itself a list of tokenized words. """ assert corpus in ['phi5', 'tlg'] if corpus == 'phi5': language = 'latin' filepaths = assemble_phi5_author_filepaths() jv_replacer = JVReplacer() text_cleaner = phi5_plaintext_cleanup word_tokenizer = nltk_tokenize_words if rm_stops: stops = latin_stops else: stops = None elif corpus == 'tlg': language = 'greek' filepaths = assemble_tlg_author_filepaths() text_cleaner = tlg_plaintext_cleanup word_tokenizer = nltk_tokenize_words if rm_stops: stops = latin_stops else: stops = None if lemmatize: lemmatizer = LemmaReplacer(language) sent_tokenizer = TokenizeSentence(language) for filepath in filepaths: with open(filepath) as f: text = f.read() # light first-pass cleanup, before sentence tokenization (which relies on punctuation) text = text_cleaner(text, rm_punctuation=False, rm_periods=False) sent_tokens = sent_tokenizer.tokenize_sentences(text) # doc_sentences = [] for sentence in sent_tokens: # a second cleanup at sentence-level, to rm all punctuation sentence = text_cleaner(sentence, rm_punctuation=True, rm_periods=True) sentence = word_tokenizer(sentence) sentence = [s.lower() for s in sentence] sentence = [w for w in sentence if w] if language == 'latin': sentence = [w[1:] if w.startswith('-') else w for w in sentence] if stops: sentence = [w for w in sentence if w not in stops] sentence = [w for w in sentence if len(w) > 1] # rm short words if sentence: sentence = sentence if lemmatize: sentence = lemmatizer.lemmatize(sentence) if sentence and language == 'latin': sentence = [jv_replacer.replace(word) for word in sentence] if sentence: yield sentence
python
def gen_docs(corpus, lemmatize, rm_stops): assert corpus in ['phi5', 'tlg'] if corpus == 'phi5': language = 'latin' filepaths = assemble_phi5_author_filepaths() jv_replacer = JVReplacer() text_cleaner = phi5_plaintext_cleanup word_tokenizer = nltk_tokenize_words if rm_stops: stops = latin_stops else: stops = None elif corpus == 'tlg': language = 'greek' filepaths = assemble_tlg_author_filepaths() text_cleaner = tlg_plaintext_cleanup word_tokenizer = nltk_tokenize_words if rm_stops: stops = latin_stops else: stops = None if lemmatize: lemmatizer = LemmaReplacer(language) sent_tokenizer = TokenizeSentence(language) for filepath in filepaths: with open(filepath) as f: text = f.read() # light first-pass cleanup, before sentence tokenization (which relies on punctuation) text = text_cleaner(text, rm_punctuation=False, rm_periods=False) sent_tokens = sent_tokenizer.tokenize_sentences(text) # doc_sentences = [] for sentence in sent_tokens: # a second cleanup at sentence-level, to rm all punctuation sentence = text_cleaner(sentence, rm_punctuation=True, rm_periods=True) sentence = word_tokenizer(sentence) sentence = [s.lower() for s in sentence] sentence = [w for w in sentence if w] if language == 'latin': sentence = [w[1:] if w.startswith('-') else w for w in sentence] if stops: sentence = [w for w in sentence if w not in stops] sentence = [w for w in sentence if len(w) > 1] # rm short words if sentence: sentence = sentence if lemmatize: sentence = lemmatizer.lemmatize(sentence) if sentence and language == 'latin': sentence = [jv_replacer.replace(word) for word in sentence] if sentence: yield sentence
[ "def", "gen_docs", "(", "corpus", ",", "lemmatize", ",", "rm_stops", ")", ":", "assert", "corpus", "in", "[", "'phi5'", ",", "'tlg'", "]", "if", "corpus", "==", "'phi5'", ":", "language", "=", "'latin'", "filepaths", "=", "assemble_phi5_author_filepaths", "(...
Open and process files from a corpus. Return a list of sentences for an author. Each sentence is itself a list of tokenized words.
[ "Open", "and", "process", "files", "from", "a", "corpus", ".", "Return", "a", "list", "of", "sentences", "for", "an", "author", ".", "Each", "sentence", "is", "itself", "a", "list", "of", "tokenized", "words", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/vector/word2vec.py#L35-L97
230,458
cltk/cltk
cltk/vector/word2vec.py
make_model
def make_model(corpus, lemmatize=False, rm_stops=False, size=100, window=10, min_count=5, workers=4, sg=1, save_path=None): """Train W2V model.""" # Simple training, with one large list t0 = time.time() sentences_stream = gen_docs(corpus, lemmatize=lemmatize, rm_stops=rm_stops) # sentences_list = [] # for sent in sentences_stream: # sentences_list.append(sent) model = Word2Vec(sentences=list(sentences_stream), size=size, window=window, min_count=min_count, workers=workers, sg=sg) # "Trim" the model of unnecessary data. Model cannot be updated anymore. model.init_sims(replace=True) if save_path: save_path = os.path.expanduser(save_path) model.save(save_path) print('Total training time for {0}: {1} minutes'.format(save_path, (time.time() - t0) / 60))
python
def make_model(corpus, lemmatize=False, rm_stops=False, size=100, window=10, min_count=5, workers=4, sg=1, save_path=None): # Simple training, with one large list t0 = time.time() sentences_stream = gen_docs(corpus, lemmatize=lemmatize, rm_stops=rm_stops) # sentences_list = [] # for sent in sentences_stream: # sentences_list.append(sent) model = Word2Vec(sentences=list(sentences_stream), size=size, window=window, min_count=min_count, workers=workers, sg=sg) # "Trim" the model of unnecessary data. Model cannot be updated anymore. model.init_sims(replace=True) if save_path: save_path = os.path.expanduser(save_path) model.save(save_path) print('Total training time for {0}: {1} minutes'.format(save_path, (time.time() - t0) / 60))
[ "def", "make_model", "(", "corpus", ",", "lemmatize", "=", "False", ",", "rm_stops", "=", "False", ",", "size", "=", "100", ",", "window", "=", "10", ",", "min_count", "=", "5", ",", "workers", "=", "4", ",", "sg", "=", "1", ",", "save_path", "=", ...
Train W2V model.
[ "Train", "W2V", "model", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/vector/word2vec.py#L103-L125
230,459
cltk/cltk
cltk/vector/word2vec.py
get_sims
def get_sims(word, language, lemmatized=False, threshold=0.70): """Get similar Word2Vec terms from vocabulary or trained model. TODO: Add option to install corpus if not available. """ # Normalize incoming word string jv_replacer = JVReplacer() if language == 'latin': # Note that casefold() seemingly does not work with diacritic # Greek, likely because of it expects single code points, not # diacritics. Look into global string normalization to code points # for all languages, especially Greek. word = jv_replacer.replace(word).casefold() model_dirs = {'greek': '~/cltk_data/greek/model/greek_word2vec_cltk', 'latin': '~/cltk_data/latin/model/latin_word2vec_cltk'} assert language in model_dirs.keys(), 'Langauges available with Word2Vec model: {}'.format(model_dirs.keys()) if lemmatized: lemma_str = '_lemmed' else: lemma_str = '' model_name = '{0}_s100_w30_min5_sg{1}.model'.format(language, lemma_str) model_dir_abs = os.path.expanduser(model_dirs[language]) model_path = os.path.join(model_dir_abs, model_name) try: model = Word2Vec.load(model_path) except FileNotFoundError as fnf_error: print(fnf_error) print("CLTK's Word2Vec models cannot be found. Please import '{}_word2vec_cltk'.".format(language)) raise try: similars = model.most_similar(word) except KeyError as key_err: print(key_err) possible_matches = [] for term in model.vocab: if term.startswith(word[:3]): possible_matches.append(term) print("The following terms in the Word2Vec model you may be looking for: '{}'.".format(possible_matches)) return None returned_sims = [] for similar in similars: if similar[1] > threshold: returned_sims.append(similar[0]) if not returned_sims: print("Matches found, but below the threshold of 'threshold={}'. Lower it to see these results.".format(threshold)) return returned_sims
python
def get_sims(word, language, lemmatized=False, threshold=0.70): # Normalize incoming word string jv_replacer = JVReplacer() if language == 'latin': # Note that casefold() seemingly does not work with diacritic # Greek, likely because of it expects single code points, not # diacritics. Look into global string normalization to code points # for all languages, especially Greek. word = jv_replacer.replace(word).casefold() model_dirs = {'greek': '~/cltk_data/greek/model/greek_word2vec_cltk', 'latin': '~/cltk_data/latin/model/latin_word2vec_cltk'} assert language in model_dirs.keys(), 'Langauges available with Word2Vec model: {}'.format(model_dirs.keys()) if lemmatized: lemma_str = '_lemmed' else: lemma_str = '' model_name = '{0}_s100_w30_min5_sg{1}.model'.format(language, lemma_str) model_dir_abs = os.path.expanduser(model_dirs[language]) model_path = os.path.join(model_dir_abs, model_name) try: model = Word2Vec.load(model_path) except FileNotFoundError as fnf_error: print(fnf_error) print("CLTK's Word2Vec models cannot be found. Please import '{}_word2vec_cltk'.".format(language)) raise try: similars = model.most_similar(word) except KeyError as key_err: print(key_err) possible_matches = [] for term in model.vocab: if term.startswith(word[:3]): possible_matches.append(term) print("The following terms in the Word2Vec model you may be looking for: '{}'.".format(possible_matches)) return None returned_sims = [] for similar in similars: if similar[1] > threshold: returned_sims.append(similar[0]) if not returned_sims: print("Matches found, but below the threshold of 'threshold={}'. Lower it to see these results.".format(threshold)) return returned_sims
[ "def", "get_sims", "(", "word", ",", "language", ",", "lemmatized", "=", "False", ",", "threshold", "=", "0.70", ")", ":", "# Normalize incoming word string", "jv_replacer", "=", "JVReplacer", "(", ")", "if", "language", "==", "'latin'", ":", "# Note that casefo...
Get similar Word2Vec terms from vocabulary or trained model. TODO: Add option to install corpus if not available.
[ "Get", "similar", "Word2Vec", "terms", "from", "vocabulary", "or", "trained", "model", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/vector/word2vec.py#L128-L174
230,460
cltk/cltk
cltk/prosody/latin/hexameter_scanner.py
HexameterScanner.invalid_foot_to_spondee
def invalid_foot_to_spondee(self, feet: list, foot: str, idx: int) -> str: """ In hexameters, a single foot that is a unstressed_stressed syllable pattern is often just a double spondee, so here we coerce it to stressed. :param feet: list of string representations of meterical feet :param foot: the bad foot to correct :param idx: the index of the foot to correct :return: corrected scansion >>> print(HexameterScanner().invalid_foot_to_spondee( ... ['-UU', '--', '-U', 'U-', '--', '-UU'],'-U', 2)) # doctest: +NORMALIZE_WHITESPACE -UU----U----UU """ new_foot = foot.replace(self.constants.UNSTRESSED, self.constants.STRESSED) feet[idx] = new_foot return "".join(feet)
python
def invalid_foot_to_spondee(self, feet: list, foot: str, idx: int) -> str: new_foot = foot.replace(self.constants.UNSTRESSED, self.constants.STRESSED) feet[idx] = new_foot return "".join(feet)
[ "def", "invalid_foot_to_spondee", "(", "self", ",", "feet", ":", "list", ",", "foot", ":", "str", ",", "idx", ":", "int", ")", "->", "str", ":", "new_foot", "=", "foot", ".", "replace", "(", "self", ".", "constants", ".", "UNSTRESSED", ",", "self", "...
In hexameters, a single foot that is a unstressed_stressed syllable pattern is often just a double spondee, so here we coerce it to stressed. :param feet: list of string representations of meterical feet :param foot: the bad foot to correct :param idx: the index of the foot to correct :return: corrected scansion >>> print(HexameterScanner().invalid_foot_to_spondee( ... ['-UU', '--', '-U', 'U-', '--', '-UU'],'-U', 2)) # doctest: +NORMALIZE_WHITESPACE -UU----U----UU
[ "In", "hexameters", "a", "single", "foot", "that", "is", "a", "unstressed_stressed", "syllable", "pattern", "is", "often", "just", "a", "double", "spondee", "so", "here", "we", "coerce", "it", "to", "stressed", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/hexameter_scanner.py#L305-L321
230,461
cltk/cltk
cltk/prosody/latin/hexameter_scanner.py
HexameterScanner.correct_dactyl_chain
def correct_dactyl_chain(self, scansion: str) -> str: """ Three or more unstressed accents in a row is a broken dactyl chain, best detected and processed backwards. Since this method takes a Procrustean approach to modifying the scansion pattern, it is not used by default in the scan method; however, it is available as an optional keyword parameter, and users looking to further automate the generation of scansion candidates should consider using this as a fall back. :param scansion: scansion with broken dactyl chain; inverted amphibrachs not allowed :return: corrected line of scansion >>> print(HexameterScanner().correct_dactyl_chain( ... "- U U - - U U - - - U U - x")) - - - - - U U - - - U U - x >>> print(HexameterScanner().correct_dactyl_chain( ... "- U U U U - - - - - U U - U")) # doctest: +NORMALIZE_WHITESPACE - - - U U - - - - - U U - U """ mark_list = string_utils.mark_list(scansion) vals = list(scansion.replace(" ", "")) # ignore last two positions, save them feet = [vals.pop(), vals.pop()] length = len(vals) idx = length - 1 while idx > 0: one = vals[idx] two = vals[idx - 1] if idx > 1: three = vals[idx - 2] else: three = "" # Dactyl foot is okay, no corrections if one == self.constants.UNSTRESSED and \ two == self.constants.UNSTRESSED and \ three == self.constants.STRESSED: feet += [one] feet += [two] feet += [three] idx -= 3 continue # Spondee foot is okay, no corrections if one == self.constants.STRESSED and \ two == self.constants.STRESSED: feet += [one] feet += [two] idx -= 2 continue # handle "U U U" foot as "- U U" if one == self.constants.UNSTRESSED and \ two == self.constants.UNSTRESSED and \ three == self.constants.UNSTRESSED: feet += [one] feet += [two] feet += [self.constants.STRESSED] idx -= 3 continue # handle "U U -" foot as "- -" if one == self.constants.STRESSED and \ two == self.constants.UNSTRESSED and \ three == self.constants.UNSTRESSED: feet += [self.constants.STRESSED] feet += [self.constants.STRESSED] idx -= 2 continue # handle "- U" foot as "- -" if one == self.constants.UNSTRESSED and \ two == self.constants.STRESSED: feet += [self.constants.STRESSED] feet += [two] idx -= 2 continue corrected = "".join(feet[::-1]) new_line = list(" " * len(scansion)) for idx, car in enumerate(corrected): new_line[mark_list[idx]] = car return "".join(new_line)
python
def correct_dactyl_chain(self, scansion: str) -> str: mark_list = string_utils.mark_list(scansion) vals = list(scansion.replace(" ", "")) # ignore last two positions, save them feet = [vals.pop(), vals.pop()] length = len(vals) idx = length - 1 while idx > 0: one = vals[idx] two = vals[idx - 1] if idx > 1: three = vals[idx - 2] else: three = "" # Dactyl foot is okay, no corrections if one == self.constants.UNSTRESSED and \ two == self.constants.UNSTRESSED and \ three == self.constants.STRESSED: feet += [one] feet += [two] feet += [three] idx -= 3 continue # Spondee foot is okay, no corrections if one == self.constants.STRESSED and \ two == self.constants.STRESSED: feet += [one] feet += [two] idx -= 2 continue # handle "U U U" foot as "- U U" if one == self.constants.UNSTRESSED and \ two == self.constants.UNSTRESSED and \ three == self.constants.UNSTRESSED: feet += [one] feet += [two] feet += [self.constants.STRESSED] idx -= 3 continue # handle "U U -" foot as "- -" if one == self.constants.STRESSED and \ two == self.constants.UNSTRESSED and \ three == self.constants.UNSTRESSED: feet += [self.constants.STRESSED] feet += [self.constants.STRESSED] idx -= 2 continue # handle "- U" foot as "- -" if one == self.constants.UNSTRESSED and \ two == self.constants.STRESSED: feet += [self.constants.STRESSED] feet += [two] idx -= 2 continue corrected = "".join(feet[::-1]) new_line = list(" " * len(scansion)) for idx, car in enumerate(corrected): new_line[mark_list[idx]] = car return "".join(new_line)
[ "def", "correct_dactyl_chain", "(", "self", ",", "scansion", ":", "str", ")", "->", "str", ":", "mark_list", "=", "string_utils", ".", "mark_list", "(", "scansion", ")", "vals", "=", "list", "(", "scansion", ".", "replace", "(", "\" \"", ",", "\"\"", ")"...
Three or more unstressed accents in a row is a broken dactyl chain, best detected and processed backwards. Since this method takes a Procrustean approach to modifying the scansion pattern, it is not used by default in the scan method; however, it is available as an optional keyword parameter, and users looking to further automate the generation of scansion candidates should consider using this as a fall back. :param scansion: scansion with broken dactyl chain; inverted amphibrachs not allowed :return: corrected line of scansion >>> print(HexameterScanner().correct_dactyl_chain( ... "- U U - - U U - - - U U - x")) - - - - - U U - - - U U - x >>> print(HexameterScanner().correct_dactyl_chain( ... "- U U U U - - - - - U U - U")) # doctest: +NORMALIZE_WHITESPACE - - - U U - - - - - U U - U
[ "Three", "or", "more", "unstressed", "accents", "in", "a", "row", "is", "a", "broken", "dactyl", "chain", "best", "detected", "and", "processed", "backwards", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/hexameter_scanner.py#L323-L400
230,462
cltk/cltk
cltk/inflection/old_norse/phonemic_rules.py
apply_raw_r_assimilation
def apply_raw_r_assimilation(last_syllable: str) -> str: """ -r preceded by an -s-, -l- or -n- becomes respectively en -s, -l or -n. >>> apply_raw_r_assimilation("arm") 'armr' >>> apply_raw_r_assimilation("ás") 'áss' >>> apply_raw_r_assimilation("stól") 'stóll' >>> apply_raw_r_assimilation("stein") 'steinn' >>> apply_raw_r_assimilation("vin") 'vinn' :param last_syllable: last syllable of an Old Norse word :return: """ if len(last_syllable) > 0: if last_syllable[-1] == "l": return last_syllable + "l" elif last_syllable[-1] == "s": return last_syllable + "s" elif last_syllable[-1] == "n": return last_syllable + "n" return last_syllable + "r"
python
def apply_raw_r_assimilation(last_syllable: str) -> str: if len(last_syllable) > 0: if last_syllable[-1] == "l": return last_syllable + "l" elif last_syllable[-1] == "s": return last_syllable + "s" elif last_syllable[-1] == "n": return last_syllable + "n" return last_syllable + "r"
[ "def", "apply_raw_r_assimilation", "(", "last_syllable", ":", "str", ")", "->", "str", ":", "if", "len", "(", "last_syllable", ")", ">", "0", ":", "if", "last_syllable", "[", "-", "1", "]", "==", "\"l\"", ":", "return", "last_syllable", "+", "\"l\"", "el...
-r preceded by an -s-, -l- or -n- becomes respectively en -s, -l or -n. >>> apply_raw_r_assimilation("arm") 'armr' >>> apply_raw_r_assimilation("ás") 'áss' >>> apply_raw_r_assimilation("stól") 'stóll' >>> apply_raw_r_assimilation("stein") 'steinn' >>> apply_raw_r_assimilation("vin") 'vinn' :param last_syllable: last syllable of an Old Norse word :return:
[ "-", "r", "preceded", "by", "an", "-", "s", "-", "-", "l", "-", "or", "-", "n", "-", "becomes", "respectively", "en", "-", "s", "-", "l", "or", "-", "n", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/inflection/old_norse/phonemic_rules.py#L92-L119
230,463
cltk/cltk
cltk/inflection/old_norse/phonemic_rules.py
add_r_ending_to_syllable
def add_r_ending_to_syllable(last_syllable: str, is_first=True) -> str: """ Adds an the -r ending to the last syllable of an Old Norse word. In some cases, it really adds an -r. In other cases, it on doubles the last character or left the syllable unchanged. >>> add_r_ending_to_syllable("arm", True) 'armr' >>> add_r_ending_to_syllable("ás", True) 'áss' >>> add_r_ending_to_syllable("stól", True) 'stóll' >>> "jö"+add_r_ending_to_syllable("kul", False) 'jökull' >>> add_r_ending_to_syllable("stein", True) 'steinn' >>> 'mi'+add_r_ending_to_syllable('kil', False) 'mikill' >>> add_r_ending_to_syllable('sæl', True) 'sæll' >>> 'li'+add_r_ending_to_syllable('til', False) 'litill' >>> add_r_ending_to_syllable('vænn', True) 'vænn' >>> add_r_ending_to_syllable('lauss', True) 'lauss' >>> add_r_ending_to_syllable("vin", True) 'vinr' >>> add_r_ending_to_syllable("sel", True) 'selr' >>> add_r_ending_to_syllable('fagr', True) 'fagr' >>> add_r_ending_to_syllable('vitr', True) 'vitr' >>> add_r_ending_to_syllable('vetr', True) 'vetr' >>> add_r_ending_to_syllable('akr', True) 'akr' >>> add_r_ending_to_syllable('Björn', True) 'Björn' >>> add_r_ending_to_syllable('þurs', True) 'þurs' >>> add_r_ending_to_syllable('karl', True) 'karl' >>> add_r_ending_to_syllable('hrafn', True) 'hrafn' :param last_syllable: last syllable of the word :param is_first: is it the first syllable of the word? :return: inflected syllable """ if len(last_syllable) >= 2: if last_syllable[-1] in ['l', 'n', 's', 'r']: if last_syllable[-2] in CONSONANTS: # Apocope of r return last_syllable else: # Assimilation of r if len(last_syllable) >= 3 and last_syllable[-3:-1] in DIPHTHONGS: return apply_raw_r_assimilation(last_syllable) elif last_syllable[-2] in SHORT_VOWELS and is_first: # No assimilation when r is supposed to be added to a stressed syllable # whose last letter is l, n or s and the penultimate letter is a short vowel return last_syllable + "r" elif last_syllable[-2] in SHORT_VOWELS: return apply_raw_r_assimilation(last_syllable) elif last_syllable[-2] in LONG_VOWELS: return apply_raw_r_assimilation(last_syllable) return apply_raw_r_assimilation(last_syllable) else: return last_syllable + "r" else: return last_syllable + "r"
python
def add_r_ending_to_syllable(last_syllable: str, is_first=True) -> str: if len(last_syllable) >= 2: if last_syllable[-1] in ['l', 'n', 's', 'r']: if last_syllable[-2] in CONSONANTS: # Apocope of r return last_syllable else: # Assimilation of r if len(last_syllable) >= 3 and last_syllable[-3:-1] in DIPHTHONGS: return apply_raw_r_assimilation(last_syllable) elif last_syllable[-2] in SHORT_VOWELS and is_first: # No assimilation when r is supposed to be added to a stressed syllable # whose last letter is l, n or s and the penultimate letter is a short vowel return last_syllable + "r" elif last_syllable[-2] in SHORT_VOWELS: return apply_raw_r_assimilation(last_syllable) elif last_syllable[-2] in LONG_VOWELS: return apply_raw_r_assimilation(last_syllable) return apply_raw_r_assimilation(last_syllable) else: return last_syllable + "r" else: return last_syllable + "r"
[ "def", "add_r_ending_to_syllable", "(", "last_syllable", ":", "str", ",", "is_first", "=", "True", ")", "->", "str", ":", "if", "len", "(", "last_syllable", ")", ">=", "2", ":", "if", "last_syllable", "[", "-", "1", "]", "in", "[", "'l'", ",", "'n'", ...
Adds an the -r ending to the last syllable of an Old Norse word. In some cases, it really adds an -r. In other cases, it on doubles the last character or left the syllable unchanged. >>> add_r_ending_to_syllable("arm", True) 'armr' >>> add_r_ending_to_syllable("ás", True) 'áss' >>> add_r_ending_to_syllable("stól", True) 'stóll' >>> "jö"+add_r_ending_to_syllable("kul", False) 'jökull' >>> add_r_ending_to_syllable("stein", True) 'steinn' >>> 'mi'+add_r_ending_to_syllable('kil', False) 'mikill' >>> add_r_ending_to_syllable('sæl', True) 'sæll' >>> 'li'+add_r_ending_to_syllable('til', False) 'litill' >>> add_r_ending_to_syllable('vænn', True) 'vænn' >>> add_r_ending_to_syllable('lauss', True) 'lauss' >>> add_r_ending_to_syllable("vin", True) 'vinr' >>> add_r_ending_to_syllable("sel", True) 'selr' >>> add_r_ending_to_syllable('fagr', True) 'fagr' >>> add_r_ending_to_syllable('vitr', True) 'vitr' >>> add_r_ending_to_syllable('vetr', True) 'vetr' >>> add_r_ending_to_syllable('akr', True) 'akr' >>> add_r_ending_to_syllable('Björn', True) 'Björn' >>> add_r_ending_to_syllable('þurs', True) 'þurs' >>> add_r_ending_to_syllable('karl', True) 'karl' >>> add_r_ending_to_syllable('hrafn', True) 'hrafn' :param last_syllable: last syllable of the word :param is_first: is it the first syllable of the word? :return: inflected syllable
[ "Adds", "an", "the", "-", "r", "ending", "to", "the", "last", "syllable", "of", "an", "Old", "Norse", "word", ".", "In", "some", "cases", "it", "really", "adds", "an", "-", "r", ".", "In", "other", "cases", "it", "on", "doubles", "the", "last", "ch...
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/inflection/old_norse/phonemic_rules.py#L122-L213
230,464
cltk/cltk
cltk/inflection/old_norse/phonemic_rules.py
add_r_ending
def add_r_ending(stem: str) -> str: """ Adds an -r ending to an Old Norse noun. >>> add_r_ending("arm") 'armr' >>> add_r_ending("ás") 'áss' >>> add_r_ending("stól") 'stóll' >>> add_r_ending("jökul") 'jökull' >>> add_r_ending("stein") 'steinn' >>> add_r_ending('mikil') 'mikill' >>> add_r_ending('sæl') 'sæll' >>> add_r_ending('litil') 'litill' >>> add_r_ending('vænn') 'vænn' >>> add_r_ending('lauss') 'lauss' >>> add_r_ending("vin") 'vinr' >>> add_r_ending("sel") 'selr' >>> add_r_ending('fagr') 'fagr' >>> add_r_ending('vitr') 'vitr' >>> add_r_ending('vetr') 'vetr' >>> add_r_ending('akr') 'akr' >>> add_r_ending('Björn') 'björn' >>> add_r_ending('þurs') 'þurs' >>> add_r_ending('karl') 'karl' >>> add_r_ending('hrafn') 'hrafn' :param stem: :return: """ s_stem = s.syllabify_ssp(stem.lower()) n_stem = len(s_stem) last_syllable = Syllable(s_stem[-1], VOWELS, CONSONANTS) return "".join(s_stem[:-1]) + add_r_ending_to_syllable(last_syllable.text, n_stem == 1)
python
def add_r_ending(stem: str) -> str: s_stem = s.syllabify_ssp(stem.lower()) n_stem = len(s_stem) last_syllable = Syllable(s_stem[-1], VOWELS, CONSONANTS) return "".join(s_stem[:-1]) + add_r_ending_to_syllable(last_syllable.text, n_stem == 1)
[ "def", "add_r_ending", "(", "stem", ":", "str", ")", "->", "str", ":", "s_stem", "=", "s", ".", "syllabify_ssp", "(", "stem", ".", "lower", "(", ")", ")", "n_stem", "=", "len", "(", "s_stem", ")", "last_syllable", "=", "Syllable", "(", "s_stem", "[",...
Adds an -r ending to an Old Norse noun. >>> add_r_ending("arm") 'armr' >>> add_r_ending("ás") 'áss' >>> add_r_ending("stól") 'stóll' >>> add_r_ending("jökul") 'jökull' >>> add_r_ending("stein") 'steinn' >>> add_r_ending('mikil') 'mikill' >>> add_r_ending('sæl') 'sæll' >>> add_r_ending('litil') 'litill' >>> add_r_ending('vænn') 'vænn' >>> add_r_ending('lauss') 'lauss' >>> add_r_ending("vin") 'vinr' >>> add_r_ending("sel") 'selr' >>> add_r_ending('fagr') 'fagr' >>> add_r_ending('vitr') 'vitr' >>> add_r_ending('vetr') 'vetr' >>> add_r_ending('akr') 'akr' >>> add_r_ending('Björn') 'björn' >>> add_r_ending('þurs') 'þurs' >>> add_r_ending('karl') 'karl' >>> add_r_ending('hrafn') 'hrafn' :param stem: :return:
[ "Adds", "an", "-", "r", "ending", "to", "an", "Old", "Norse", "noun", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/inflection/old_norse/phonemic_rules.py#L216-L286
230,465
cltk/cltk
cltk/inflection/old_norse/phonemic_rules.py
apply_i_umlaut
def apply_i_umlaut(stem: str): """ Changes the vowel of the last syllable of the given stem according to an i-umlaut. >>> apply_i_umlaut("mæl") 'mæl' >>> apply_i_umlaut("lagð") 'legð' >>> apply_i_umlaut("vak") 'vek' >>> apply_i_umlaut("haf") 'hef' >>> apply_i_umlaut("buð") 'byð' >>> apply_i_umlaut("bár") 'bær' >>> apply_i_umlaut("réð") 'réð' >>> apply_i_umlaut("fór") 'fœr' :param stem: :return: """ assert len(stem) > 0 s_stem = s.syllabify_ssp(stem.lower()) last_syllable = OldNorseSyllable(s_stem[-1], VOWELS, CONSONANTS) last_syllable.apply_i_umlaut() return "".join(s_stem[:-1]) + str(last_syllable)
python
def apply_i_umlaut(stem: str): assert len(stem) > 0 s_stem = s.syllabify_ssp(stem.lower()) last_syllable = OldNorseSyllable(s_stem[-1], VOWELS, CONSONANTS) last_syllable.apply_i_umlaut() return "".join(s_stem[:-1]) + str(last_syllable)
[ "def", "apply_i_umlaut", "(", "stem", ":", "str", ")", ":", "assert", "len", "(", "stem", ")", ">", "0", "s_stem", "=", "s", ".", "syllabify_ssp", "(", "stem", ".", "lower", "(", ")", ")", "last_syllable", "=", "OldNorseSyllable", "(", "s_stem", "[", ...
Changes the vowel of the last syllable of the given stem according to an i-umlaut. >>> apply_i_umlaut("mæl") 'mæl' >>> apply_i_umlaut("lagð") 'legð' >>> apply_i_umlaut("vak") 'vek' >>> apply_i_umlaut("haf") 'hef' >>> apply_i_umlaut("buð") 'byð' >>> apply_i_umlaut("bár") 'bær' >>> apply_i_umlaut("réð") 'réð' >>> apply_i_umlaut("fór") 'fœr' :param stem: :return:
[ "Changes", "the", "vowel", "of", "the", "last", "syllable", "of", "the", "given", "stem", "according", "to", "an", "i", "-", "umlaut", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/inflection/old_norse/phonemic_rules.py#L315-L343
230,466
cltk/cltk
cltk/prosody/latin/hendecasyllable_scanner.py
HendecasyllableScanner.correct_invalid_start
def correct_invalid_start(self, scansion: str) -> str: """ The third syllable of a hendecasyllabic line is long, so we will convert it. :param scansion: scansion string :return: scansion string with corrected start >>> print(HendecasyllableScanner().correct_invalid_start( ... "- U U U U - U - U - U").strip()) - U - U U - U - U - U """ mark_list = string_utils.mark_list(scansion) vals = list(scansion.replace(" ", "")) corrected = vals[:2] + [self.constants.STRESSED] + vals[3:] new_line = list(" " * len(scansion)) for idx, car in enumerate(corrected): new_line[mark_list[idx]] = car return "".join(new_line)
python
def correct_invalid_start(self, scansion: str) -> str: mark_list = string_utils.mark_list(scansion) vals = list(scansion.replace(" ", "")) corrected = vals[:2] + [self.constants.STRESSED] + vals[3:] new_line = list(" " * len(scansion)) for idx, car in enumerate(corrected): new_line[mark_list[idx]] = car return "".join(new_line)
[ "def", "correct_invalid_start", "(", "self", ",", "scansion", ":", "str", ")", "->", "str", ":", "mark_list", "=", "string_utils", ".", "mark_list", "(", "scansion", ")", "vals", "=", "list", "(", "scansion", ".", "replace", "(", "\" \"", ",", "\"\"", ")...
The third syllable of a hendecasyllabic line is long, so we will convert it. :param scansion: scansion string :return: scansion string with corrected start >>> print(HendecasyllableScanner().correct_invalid_start( ... "- U U U U - U - U - U").strip()) - U - U U - U - U - U
[ "The", "third", "syllable", "of", "a", "hendecasyllabic", "line", "is", "long", "so", "we", "will", "convert", "it", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/hendecasyllable_scanner.py#L152-L169
230,467
cltk/cltk
cltk/lemmatize/backoff.py
SequentialBackoffLemmatizer.tag_one
def tag_one(self: object, tokens: List[str], index: int, history: List[str]): """ Determine an appropriate tag for the specified token, and return that tag. If this tagger is unable to determine a tag for the specified token, then its backoff tagger is consulted. :rtype: tuple :type tokens: list :param tokens: The list of words that are being tagged. :type index: int :param index: The index of the word whose tag should be returned. :type history: list(str) :param history: A list of the tags for all words before index. """ lemma = None for tagger in self._taggers: lemma = tagger.choose_tag(tokens, index, history) if lemma is not None: break return lemma, tagger
python
def tag_one(self: object, tokens: List[str], index: int, history: List[str]): lemma = None for tagger in self._taggers: lemma = tagger.choose_tag(tokens, index, history) if lemma is not None: break return lemma, tagger
[ "def", "tag_one", "(", "self", ":", "object", ",", "tokens", ":", "List", "[", "str", "]", ",", "index", ":", "int", ",", "history", ":", "List", "[", "str", "]", ")", ":", "lemma", "=", "None", "for", "tagger", "in", "self", ".", "_taggers", ":"...
Determine an appropriate tag for the specified token, and return that tag. If this tagger is unable to determine a tag for the specified token, then its backoff tagger is consulted. :rtype: tuple :type tokens: list :param tokens: The list of words that are being tagged. :type index: int :param index: The index of the word whose tag should be returned. :type history: list(str) :param history: A list of the tags for all words before index.
[ "Determine", "an", "appropriate", "tag", "for", "the", "specified", "token", "and", "return", "that", "tag", ".", "If", "this", "tagger", "is", "unable", "to", "determine", "a", "tag", "for", "the", "specified", "token", "then", "its", "backoff", "tagger", ...
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/lemmatize/backoff.py#L99-L119
230,468
cltk/cltk
cltk/tokenize/word.py
tokenize_akkadian_words
def tokenize_akkadian_words(line): """ Operates on a single line of text, returns all words in the line as a tuple in a list. input: "1. isz-pur-ram a-na" output: [("isz-pur-ram", "akkadian"), ("a-na", "akkadian")] :param: line: text string :return: list of tuples: (word, language) """ beginning_underscore = "_[^_]+(?!_)$" # only match a string if it has a beginning underscore anywhere ending_underscore = "^(?<!_)[^_]+_" # only match a string if it has an ending underscore anywhere two_underscores = "_[^_]+_" # only match a string if it has two underscores words = line.split() # split the line on spaces ignoring the first split (which is the # line number) language = "akkadian" output_words = [] for word in words: if re.search(two_underscores, word): # If the string has two underscores in it then the word is # in Sumerian while the neighboring words are in Akkadian. output_words.append((word, "sumerian")) elif re.search(beginning_underscore, word): # If the word has an initial underscore somewhere # but no other underscores than we're starting a block # of Sumerian. language = "sumerian" output_words.append((word, language)) elif re.search(ending_underscore, word): # If the word has an ending underscore somewhere # but not other underscores than we're ending a block # of Sumerian. output_words.append((word, language)) language = "akkadian" else: # If there are no underscore than we are continuing # whatever language we're currently in. output_words.append((word, language)) return output_words
python
def tokenize_akkadian_words(line): beginning_underscore = "_[^_]+(?!_)$" # only match a string if it has a beginning underscore anywhere ending_underscore = "^(?<!_)[^_]+_" # only match a string if it has an ending underscore anywhere two_underscores = "_[^_]+_" # only match a string if it has two underscores words = line.split() # split the line on spaces ignoring the first split (which is the # line number) language = "akkadian" output_words = [] for word in words: if re.search(two_underscores, word): # If the string has two underscores in it then the word is # in Sumerian while the neighboring words are in Akkadian. output_words.append((word, "sumerian")) elif re.search(beginning_underscore, word): # If the word has an initial underscore somewhere # but no other underscores than we're starting a block # of Sumerian. language = "sumerian" output_words.append((word, language)) elif re.search(ending_underscore, word): # If the word has an ending underscore somewhere # but not other underscores than we're ending a block # of Sumerian. output_words.append((word, language)) language = "akkadian" else: # If there are no underscore than we are continuing # whatever language we're currently in. output_words.append((word, language)) return output_words
[ "def", "tokenize_akkadian_words", "(", "line", ")", ":", "beginning_underscore", "=", "\"_[^_]+(?!_)$\"", "# only match a string if it has a beginning underscore anywhere", "ending_underscore", "=", "\"^(?<!_)[^_]+_\"", "# only match a string if it has an ending underscore anywhere", "tw...
Operates on a single line of text, returns all words in the line as a tuple in a list. input: "1. isz-pur-ram a-na" output: [("isz-pur-ram", "akkadian"), ("a-na", "akkadian")] :param: line: text string :return: list of tuples: (word, language)
[ "Operates", "on", "a", "single", "line", "of", "text", "returns", "all", "words", "in", "the", "line", "as", "a", "tuple", "in", "a", "list", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/tokenize/word.py#L111-L155
230,469
cltk/cltk
cltk/tokenize/word.py
tokenize_arabic_words
def tokenize_arabic_words(text): """ Tokenize text into words @param text: the input text. @type text: unicode. @return: list of words. @rtype: list. """ specific_tokens = [] if not text: return specific_tokens else: specific_tokens = araby.tokenize(text) return specific_tokens
python
def tokenize_arabic_words(text): specific_tokens = [] if not text: return specific_tokens else: specific_tokens = araby.tokenize(text) return specific_tokens
[ "def", "tokenize_arabic_words", "(", "text", ")", ":", "specific_tokens", "=", "[", "]", "if", "not", "text", ":", "return", "specific_tokens", "else", ":", "specific_tokens", "=", "araby", ".", "tokenize", "(", "text", ")", "return", "specific_tokens" ]
Tokenize text into words @param text: the input text. @type text: unicode. @return: list of words. @rtype: list.
[ "Tokenize", "text", "into", "words" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/tokenize/word.py#L235-L249
230,470
cltk/cltk
cltk/tokenize/word.py
tokenize_middle_high_german_words
def tokenize_middle_high_german_words(text): """Tokenizes MHG text""" assert isinstance(text, str) # As far as I know, hyphens were never used for compounds, so the tokenizer treats all hyphens as line-breaks text = re.sub(r'-\n',r'-', text) text = re.sub(r'\n', r' ', text) text = re.sub(r'(?<=.)(?=[\.\";\,\:\[\]\(\)!&?])',r' ', text) text = re.sub(r'(?<=[\.\";\,\:\[\]\(\)!&?])(?=.)',r' ', text) text = re.sub(r'\s+',r' ', text) text = str.split(text) return text
python
def tokenize_middle_high_german_words(text): assert isinstance(text, str) # As far as I know, hyphens were never used for compounds, so the tokenizer treats all hyphens as line-breaks text = re.sub(r'-\n',r'-', text) text = re.sub(r'\n', r' ', text) text = re.sub(r'(?<=.)(?=[\.\";\,\:\[\]\(\)!&?])',r' ', text) text = re.sub(r'(?<=[\.\";\,\:\[\]\(\)!&?])(?=.)',r' ', text) text = re.sub(r'\s+',r' ', text) text = str.split(text) return text
[ "def", "tokenize_middle_high_german_words", "(", "text", ")", ":", "assert", "isinstance", "(", "text", ",", "str", ")", "# As far as I know, hyphens were never used for compounds, so the tokenizer treats all hyphens as line-breaks", "text", "=", "re", ".", "sub", "(", "r'-\\...
Tokenizes MHG text
[ "Tokenizes", "MHG", "text" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/tokenize/word.py#L433-L445
230,471
cltk/cltk
cltk/tokenize/word.py
WordTokenizer.tokenize
def tokenize(self, string): """Tokenize incoming string.""" if self.language == 'akkadian': tokens = tokenize_akkadian_words(string) elif self.language == 'arabic': tokens = tokenize_arabic_words(string) elif self.language == 'french': tokens = tokenize_french_words(string) elif self.language == 'greek': tokens = tokenize_greek_words(string) elif self.language == 'latin': tokens = tokenize_latin_words(string) elif self.language == 'old_norse': tokens = tokenize_old_norse_words(string) elif self.language == 'middle_english': tokens = tokenize_middle_english_words(string) elif self.language == 'middle_high_german': tokens = tokenize_middle_high_german_words(string) else: tokens = nltk_tokenize_words(string) return tokens
python
def tokenize(self, string): if self.language == 'akkadian': tokens = tokenize_akkadian_words(string) elif self.language == 'arabic': tokens = tokenize_arabic_words(string) elif self.language == 'french': tokens = tokenize_french_words(string) elif self.language == 'greek': tokens = tokenize_greek_words(string) elif self.language == 'latin': tokens = tokenize_latin_words(string) elif self.language == 'old_norse': tokens = tokenize_old_norse_words(string) elif self.language == 'middle_english': tokens = tokenize_middle_english_words(string) elif self.language == 'middle_high_german': tokens = tokenize_middle_high_german_words(string) else: tokens = nltk_tokenize_words(string) return tokens
[ "def", "tokenize", "(", "self", ",", "string", ")", ":", "if", "self", ".", "language", "==", "'akkadian'", ":", "tokens", "=", "tokenize_akkadian_words", "(", "string", ")", "elif", "self", ".", "language", "==", "'arabic'", ":", "tokens", "=", "tokenize_...
Tokenize incoming string.
[ "Tokenize", "incoming", "string", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/tokenize/word.py#L39-L61
230,472
cltk/cltk
cltk/tokenize/word.py
WordTokenizer.tokenize_sign
def tokenize_sign(self, word): """This is for tokenizing cuneiform signs.""" if self.language == 'akkadian': sign_tokens = tokenize_akkadian_signs(word) else: sign_tokens = 'Language must be written using cuneiform.' return sign_tokens
python
def tokenize_sign(self, word): if self.language == 'akkadian': sign_tokens = tokenize_akkadian_signs(word) else: sign_tokens = 'Language must be written using cuneiform.' return sign_tokens
[ "def", "tokenize_sign", "(", "self", ",", "word", ")", ":", "if", "self", ".", "language", "==", "'akkadian'", ":", "sign_tokens", "=", "tokenize_akkadian_signs", "(", "word", ")", "else", ":", "sign_tokens", "=", "'Language must be written using cuneiform.'", "re...
This is for tokenizing cuneiform signs.
[ "This", "is", "for", "tokenizing", "cuneiform", "signs", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/tokenize/word.py#L63-L70
230,473
cltk/cltk
cltk/corpus/greek/tlgu.py
TLGU._check_import_source
def _check_import_source(): """Check if tlgu imported, if not import it.""" path_rel = '~/cltk_data/greek/software/greek_software_tlgu/tlgu.h' path = os.path.expanduser(path_rel) if not os.path.isfile(path): try: corpus_importer = CorpusImporter('greek') corpus_importer.import_corpus('greek_software_tlgu') except Exception as exc: logger.error('Failed to import TLGU: %s', exc) raise
python
def _check_import_source(): path_rel = '~/cltk_data/greek/software/greek_software_tlgu/tlgu.h' path = os.path.expanduser(path_rel) if not os.path.isfile(path): try: corpus_importer = CorpusImporter('greek') corpus_importer.import_corpus('greek_software_tlgu') except Exception as exc: logger.error('Failed to import TLGU: %s', exc) raise
[ "def", "_check_import_source", "(", ")", ":", "path_rel", "=", "'~/cltk_data/greek/software/greek_software_tlgu/tlgu.h'", "path", "=", "os", ".", "path", ".", "expanduser", "(", "path_rel", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "path", ")", ...
Check if tlgu imported, if not import it.
[ "Check", "if", "tlgu", "imported", "if", "not", "import", "it", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/greek/tlgu.py#L48-L58
230,474
cltk/cltk
cltk/corpus/greek/tlgu.py
TLGU._check_install
def _check_install(self): """Check if tlgu installed, if not install it.""" try: subprocess.check_output(['which', 'tlgu']) except Exception as exc: logger.info('TLGU not installed: %s', exc) logger.info('Installing TLGU.') if not subprocess.check_output(['which', 'gcc']): logger.error('GCC seems not to be installed.') else: tlgu_path_rel = '~/cltk_data/greek/software/greek_software_tlgu' tlgu_path = os.path.expanduser(tlgu_path_rel) if not self.testing: print('Do you want to install TLGU?') print('To continue, press Return. To exit, Control-C.') input() else: print('Automated or test build, skipping keyboard input confirmation for installation of TLGU.') try: command = 'cd {0} && make install'.format(tlgu_path) print('Going to run command:', command) p_out = subprocess.call(command, shell=True) if p_out == 0: logger.info('TLGU installed.') else: logger.error('TLGU install without sudo failed.') except Exception as exc: logger.error('TLGU install failed: %s', exc) else: # for Linux needing root access to '/usr/local/bin' if not self.testing: print('Could not install without root access. Do you want to install TLGU with sudo?') command = 'cd {0} && sudo make install'.format(tlgu_path) print('Going to run command:', command) print('To continue, press Return. To exit, Control-C.') input() p_out = subprocess.call(command, shell=True) else: command = 'cd {0} && sudo make install'.format(tlgu_path) p_out = subprocess.call(command, shell=True) if p_out == 0: logger.info('TLGU installed.') else: logger.error('TLGU install with sudo failed.')
python
def _check_install(self): try: subprocess.check_output(['which', 'tlgu']) except Exception as exc: logger.info('TLGU not installed: %s', exc) logger.info('Installing TLGU.') if not subprocess.check_output(['which', 'gcc']): logger.error('GCC seems not to be installed.') else: tlgu_path_rel = '~/cltk_data/greek/software/greek_software_tlgu' tlgu_path = os.path.expanduser(tlgu_path_rel) if not self.testing: print('Do you want to install TLGU?') print('To continue, press Return. To exit, Control-C.') input() else: print('Automated or test build, skipping keyboard input confirmation for installation of TLGU.') try: command = 'cd {0} && make install'.format(tlgu_path) print('Going to run command:', command) p_out = subprocess.call(command, shell=True) if p_out == 0: logger.info('TLGU installed.') else: logger.error('TLGU install without sudo failed.') except Exception as exc: logger.error('TLGU install failed: %s', exc) else: # for Linux needing root access to '/usr/local/bin' if not self.testing: print('Could not install without root access. Do you want to install TLGU with sudo?') command = 'cd {0} && sudo make install'.format(tlgu_path) print('Going to run command:', command) print('To continue, press Return. To exit, Control-C.') input() p_out = subprocess.call(command, shell=True) else: command = 'cd {0} && sudo make install'.format(tlgu_path) p_out = subprocess.call(command, shell=True) if p_out == 0: logger.info('TLGU installed.') else: logger.error('TLGU install with sudo failed.')
[ "def", "_check_install", "(", "self", ")", ":", "try", ":", "subprocess", ".", "check_output", "(", "[", "'which'", ",", "'tlgu'", "]", ")", "except", "Exception", "as", "exc", ":", "logger", ".", "info", "(", "'TLGU not installed: %s'", ",", "exc", ")", ...
Check if tlgu installed, if not install it.
[ "Check", "if", "tlgu", "installed", "if", "not", "install", "it", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/greek/tlgu.py#L60-L102
230,475
cltk/cltk
cltk/stem/latin/syllabifier.py
Syllabifier.syllabify
def syllabify(self, word): """Splits input Latin word into a list of syllables, based on the language syllables loaded for the Syllabifier instance""" prefixes = self.language['single_syllable_prefixes'] prefixes.sort(key=len, reverse=True) # Check if word is in exception dictionary if word in self.language['exceptions']: syllables = self.language['exceptions'][word] # Else, breakdown syllables for word else: syllables = [] # Remove prefixes for prefix in prefixes: if word.startswith(prefix): syllables.append(prefix) word = re.sub('^%s' % prefix, '', word) break # Initialize syllable to build by iterating through over characters syllable = '' # Get word length for determining character position in word word_len = len(word) # Iterate over characters to build syllables for i, char in enumerate(word): # Build syllable syllable = syllable + char syllable_complete = False # Checks to process syllable logic char_is_vowel = self._is_vowel(char) has_next_char = i < word_len - 1 has_prev_char = i > 0 # If it's the end of the word, the syllable is complete if not has_next_char: syllable_complete = True else: next_char = word[i + 1] if has_prev_char: prev_char = word[i - 1] # 'i' is a special case for a vowel. when i is at the # beginning of the word (Iesu) or i is between # vowels (alleluia), then the i is treated as a # consonant (y) Note: what about compounds like 'adiungere' if char == 'i' and has_next_char and self._is_vowel(next_char): if i == 0: char_is_vowel = False elif self._is_vowel(prev_char): char_is_vowel = False # Determine if the syllable is complete if char_is_vowel: if ( ( # If the next character's a vowel self._is_vowel( next_char) # And it doesn't compose a dipthong with the current character and not self._is_diphthong(char, next_char) # And the current character isn't preceded by a q, unless followed by a u and not ( has_prev_char and prev_char == "q" and char == "u" and next_char != "u" ) ) or ( # If the next character's a consonant but not a double consonant, unless it's a mute consonant followed by a liquid consonant i < word_len - 2 and ( ( ( has_prev_char and prev_char != "q" and char == "u" and self._is_vowel(word[i + 2]) ) or ( not has_prev_char and char == "u" and self._is_vowel(word[i + 2]) ) ) or ( char != "u" and self._is_vowel(word[i + 2]) and not self._is_diphthong(char, next_char) ) or ( self._is_mute_consonant_or_f(next_char) and self._is_liquid_consonant(word[i + 2]) ) ) ) ): syllable_complete = True # Otherwise, it's a consonant else: if ( # If the next character's also a consonant (but it's not the last in the word) ( not self._is_vowel(next_char) and i < word_len - 2 ) # If the char's not a mute consonant followed by a liquid consonant and not ( self._is_mute_consonant_or_f(char) and self._is_liquid_consonant(next_char) ) # If the char's not a c, p, or t followed by an h and not ( ( has_prev_char and not self._is_vowel(prev_char) and char in ['c', 'p', 't'] and next_char == 'h' ) or ( not has_prev_char and char in ['c', 'p', 't'] and next_char == 'h' ) ) # And it's not the only letter in the syllable and not len(syllable) == 1 ): syllable_complete = True # If it's a complete syllable, append it to syllables list and reset syllable if syllable_complete: syllables.append(syllable) syllable = '' return syllables
python
def syllabify(self, word): prefixes = self.language['single_syllable_prefixes'] prefixes.sort(key=len, reverse=True) # Check if word is in exception dictionary if word in self.language['exceptions']: syllables = self.language['exceptions'][word] # Else, breakdown syllables for word else: syllables = [] # Remove prefixes for prefix in prefixes: if word.startswith(prefix): syllables.append(prefix) word = re.sub('^%s' % prefix, '', word) break # Initialize syllable to build by iterating through over characters syllable = '' # Get word length for determining character position in word word_len = len(word) # Iterate over characters to build syllables for i, char in enumerate(word): # Build syllable syllable = syllable + char syllable_complete = False # Checks to process syllable logic char_is_vowel = self._is_vowel(char) has_next_char = i < word_len - 1 has_prev_char = i > 0 # If it's the end of the word, the syllable is complete if not has_next_char: syllable_complete = True else: next_char = word[i + 1] if has_prev_char: prev_char = word[i - 1] # 'i' is a special case for a vowel. when i is at the # beginning of the word (Iesu) or i is between # vowels (alleluia), then the i is treated as a # consonant (y) Note: what about compounds like 'adiungere' if char == 'i' and has_next_char and self._is_vowel(next_char): if i == 0: char_is_vowel = False elif self._is_vowel(prev_char): char_is_vowel = False # Determine if the syllable is complete if char_is_vowel: if ( ( # If the next character's a vowel self._is_vowel( next_char) # And it doesn't compose a dipthong with the current character and not self._is_diphthong(char, next_char) # And the current character isn't preceded by a q, unless followed by a u and not ( has_prev_char and prev_char == "q" and char == "u" and next_char != "u" ) ) or ( # If the next character's a consonant but not a double consonant, unless it's a mute consonant followed by a liquid consonant i < word_len - 2 and ( ( ( has_prev_char and prev_char != "q" and char == "u" and self._is_vowel(word[i + 2]) ) or ( not has_prev_char and char == "u" and self._is_vowel(word[i + 2]) ) ) or ( char != "u" and self._is_vowel(word[i + 2]) and not self._is_diphthong(char, next_char) ) or ( self._is_mute_consonant_or_f(next_char) and self._is_liquid_consonant(word[i + 2]) ) ) ) ): syllable_complete = True # Otherwise, it's a consonant else: if ( # If the next character's also a consonant (but it's not the last in the word) ( not self._is_vowel(next_char) and i < word_len - 2 ) # If the char's not a mute consonant followed by a liquid consonant and not ( self._is_mute_consonant_or_f(char) and self._is_liquid_consonant(next_char) ) # If the char's not a c, p, or t followed by an h and not ( ( has_prev_char and not self._is_vowel(prev_char) and char in ['c', 'p', 't'] and next_char == 'h' ) or ( not has_prev_char and char in ['c', 'p', 't'] and next_char == 'h' ) ) # And it's not the only letter in the syllable and not len(syllable) == 1 ): syllable_complete = True # If it's a complete syllable, append it to syllables list and reset syllable if syllable_complete: syllables.append(syllable) syllable = '' return syllables
[ "def", "syllabify", "(", "self", ",", "word", ")", ":", "prefixes", "=", "self", ".", "language", "[", "'single_syllable_prefixes'", "]", "prefixes", ".", "sort", "(", "key", "=", "len", ",", "reverse", "=", "True", ")", "# Check if word is in exception dictio...
Splits input Latin word into a list of syllables, based on the language syllables loaded for the Syllabifier instance
[ "Splits", "input", "Latin", "word", "into", "a", "list", "of", "syllables", "based", "on", "the", "language", "syllables", "loaded", "for", "the", "Syllabifier", "instance" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/stem/latin/syllabifier.py#L115-L257
230,476
cltk/cltk
cltk/prosody/greek/scanner.py
Scansion._clean_text
def _clean_text(self, text): """Clean the text of extraneous punction. By default, ':', ';', and '.' are defined as stops. :param text: raw text :return: clean text :rtype : string """ clean = [] for char in text: if char in self.punc_stops: clean += '.' elif char not in self.punc: clean += char else: pass return (''.join(clean)).lower()
python
def _clean_text(self, text): clean = [] for char in text: if char in self.punc_stops: clean += '.' elif char not in self.punc: clean += char else: pass return (''.join(clean)).lower()
[ "def", "_clean_text", "(", "self", ",", "text", ")", ":", "clean", "=", "[", "]", "for", "char", "in", "text", ":", "if", "char", "in", "self", ".", "punc_stops", ":", "clean", "+=", "'.'", "elif", "char", "not", "in", "self", ".", "punc", ":", "...
Clean the text of extraneous punction. By default, ':', ';', and '.' are defined as stops. :param text: raw text :return: clean text :rtype : string
[ "Clean", "the", "text", "of", "extraneous", "punction", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/greek/scanner.py#L46-L62
230,477
cltk/cltk
cltk/prosody/greek/scanner.py
Scansion._tokenize
def _tokenize(self, text): """Tokenize the text into a list of sentences with a list of words. :param text: raw text :return: tokenized text :rtype : list """ sentences = [] tokens = [] for word in self._clean_accents(text).split(' '): tokens.append(word) if '.' in word: sentences.append(tokens) tokens = [] return sentences
python
def _tokenize(self, text): sentences = [] tokens = [] for word in self._clean_accents(text).split(' '): tokens.append(word) if '.' in word: sentences.append(tokens) tokens = [] return sentences
[ "def", "_tokenize", "(", "self", ",", "text", ")", ":", "sentences", "=", "[", "]", "tokens", "=", "[", "]", "for", "word", "in", "self", ".", "_clean_accents", "(", "text", ")", ".", "split", "(", "' '", ")", ":", "tokens", ".", "append", "(", "...
Tokenize the text into a list of sentences with a list of words. :param text: raw text :return: tokenized text :rtype : list
[ "Tokenize", "the", "text", "into", "a", "list", "of", "sentences", "with", "a", "list", "of", "words", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/greek/scanner.py#L94-L108
230,478
cltk/cltk
cltk/prosody/greek/scanner.py
Scansion._long_by_nature
def _long_by_nature(self, syllable): """Check if syllable is long by nature. Long by nature includes: 1) Syllable contains a diphthong 2) Syllable contains a long vowel :param syllable: current syllable :return: True if long by nature :rtype : bool """ # Find diphthongs vowel_group = [] for char in syllable: print if char in self.long_vowels: return True elif char not in self.sing_cons and char not in self.doub_cons: vowel_group += char if ''.join(vowel_group) in self.diphthongs: return True
python
def _long_by_nature(self, syllable): # Find diphthongs vowel_group = [] for char in syllable: print if char in self.long_vowels: return True elif char not in self.sing_cons and char not in self.doub_cons: vowel_group += char if ''.join(vowel_group) in self.diphthongs: return True
[ "def", "_long_by_nature", "(", "self", ",", "syllable", ")", ":", "# Find diphthongs", "vowel_group", "=", "[", "]", "for", "char", "in", "syllable", ":", "print", "if", "char", "in", "self", ".", "long_vowels", ":", "return", "True", "elif", "char", "not"...
Check if syllable is long by nature. Long by nature includes: 1) Syllable contains a diphthong 2) Syllable contains a long vowel :param syllable: current syllable :return: True if long by nature :rtype : bool
[ "Check", "if", "syllable", "is", "long", "by", "nature", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/greek/scanner.py#L125-L145
230,479
cltk/cltk
cltk/prosody/greek/scanner.py
Scansion._long_by_position
def _long_by_position(self, syllable, sentence): """Check if syllable is long by position. Long by position includes: 1) Next syllable begins with two consonants, unless those consonants are a stop + liquid combination 2) Next syllable begins with a double consonant 3) Syllable ends with a consonant and the next syllable begins with a consonant :param syllable: Current syllable :param sentence: Current sentence :return: True if syllable is long by position :rtype : bool """ try: next_syll = sentence[sentence.index(syllable) + 1] # Long by position by case 1 if (next_syll[0] in self.sing_cons and next_syll[1] in self.sing_cons) and (next_syll[0] not in self.stops and next_syll[1] not in self.liquids): return True # Long by position by case 2 elif syllable[-1] in self.vowels and next_syll[0] in self.doub_cons: return True # Long by position by case 3 elif syllable[-1] in self.sing_cons and (next_syll[0] in self.sing_cons): return True else: pass except IndexError: logger.info("IndexError while checking if syllable '%s' is long. Continuing.", syllable)
python
def _long_by_position(self, syllable, sentence): try: next_syll = sentence[sentence.index(syllable) + 1] # Long by position by case 1 if (next_syll[0] in self.sing_cons and next_syll[1] in self.sing_cons) and (next_syll[0] not in self.stops and next_syll[1] not in self.liquids): return True # Long by position by case 2 elif syllable[-1] in self.vowels and next_syll[0] in self.doub_cons: return True # Long by position by case 3 elif syllable[-1] in self.sing_cons and (next_syll[0] in self.sing_cons): return True else: pass except IndexError: logger.info("IndexError while checking if syllable '%s' is long. Continuing.", syllable)
[ "def", "_long_by_position", "(", "self", ",", "syllable", ",", "sentence", ")", ":", "try", ":", "next_syll", "=", "sentence", "[", "sentence", ".", "index", "(", "syllable", ")", "+", "1", "]", "# Long by position by case 1", "if", "(", "next_syll", "[", ...
Check if syllable is long by position. Long by position includes: 1) Next syllable begins with two consonants, unless those consonants are a stop + liquid combination 2) Next syllable begins with a double consonant 3) Syllable ends with a consonant and the next syllable begins with a consonant :param syllable: Current syllable :param sentence: Current sentence :return: True if syllable is long by position :rtype : bool
[ "Check", "if", "syllable", "is", "long", "by", "position", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/greek/scanner.py#L147-L177
230,480
cltk/cltk
cltk/prosody/greek/scanner.py
Scansion.scan_text
def scan_text(self, input_string): """The primary method for the class. :param input_string: A string of macronized text. :return: meter of text :rtype : list """ syllables = self._make_syllables(input_string) sentence_syllables = self._syllable_condenser(syllables) meter = self._scansion(sentence_syllables) return meter
python
def scan_text(self, input_string): syllables = self._make_syllables(input_string) sentence_syllables = self._syllable_condenser(syllables) meter = self._scansion(sentence_syllables) return meter
[ "def", "scan_text", "(", "self", ",", "input_string", ")", ":", "syllables", "=", "self", ".", "_make_syllables", "(", "input_string", ")", "sentence_syllables", "=", "self", ".", "_syllable_condenser", "(", "syllables", ")", "meter", "=", "self", ".", "_scans...
The primary method for the class. :param input_string: A string of macronized text. :return: meter of text :rtype : list
[ "The", "primary", "method", "for", "the", "class", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/greek/scanner.py#L255-L265
230,481
cltk/cltk
cltk/stem/latin/stem.py
Stemmer.stem
def stem(self, text): """Stem each word of the Latin text.""" stemmed_text = '' for word in text.split(' '): if word not in self.stops: # remove '-que' suffix word, in_que_pass_list = self._checkremove_que(word) if not in_que_pass_list: # remove the simple endings from the target word word, was_stemmed = self._matchremove_simple_endings(word) # if word didn't match the simple endings, try verb endings if not was_stemmed: word = self._matchremove_verb_endings(word) # add the stemmed word to the text stemmed_text += word + ' ' return stemmed_text
python
def stem(self, text): stemmed_text = '' for word in text.split(' '): if word not in self.stops: # remove '-que' suffix word, in_que_pass_list = self._checkremove_que(word) if not in_que_pass_list: # remove the simple endings from the target word word, was_stemmed = self._matchremove_simple_endings(word) # if word didn't match the simple endings, try verb endings if not was_stemmed: word = self._matchremove_verb_endings(word) # add the stemmed word to the text stemmed_text += word + ' ' return stemmed_text
[ "def", "stem", "(", "self", ",", "text", ")", ":", "stemmed_text", "=", "''", "for", "word", "in", "text", ".", "split", "(", "' '", ")", ":", "if", "word", "not", "in", "self", ".", "stops", ":", "# remove '-que' suffix", "word", ",", "in_que_pass_lis...
Stem each word of the Latin text.
[ "Stem", "each", "word", "of", "the", "Latin", "text", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/stem/latin/stem.py#L24-L47
230,482
cltk/cltk
cltk/stem/latin/stem.py
Stemmer._checkremove_que
def _checkremove_que(self, word): """If word ends in -que and if word is not in pass list, strip -que""" in_que_pass_list = False que_pass_list = ['atque', 'quoque', 'neque', 'itaque', 'absque', 'apsque', 'abusque', 'adaeque', 'adusque', 'denique', 'deque', 'susque', 'oblique', 'peraeque', 'plenisque', 'quandoque', 'quisque', 'quaeque', 'cuiusque', 'cuique', 'quemque', 'quamque', 'quaque', 'quique', 'quorumque', 'quarumque', 'quibusque', 'quosque', 'quasque', 'quotusquisque', 'quousque', 'ubique', 'undique', 'usque', 'uterque', 'utique', 'utroque', 'utribique', 'torque', 'coque', 'concoque', 'contorque', 'detorque', 'decoque', 'excoque', 'extorque', 'obtorque', 'optorque', 'retorque', 'recoque', 'attorque', 'incoque', 'intorque', 'praetorque'] if word not in que_pass_list: word = re.sub(r'que$', '', word) else: in_que_pass_list = True return word, in_que_pass_list
python
def _checkremove_que(self, word): in_que_pass_list = False que_pass_list = ['atque', 'quoque', 'neque', 'itaque', 'absque', 'apsque', 'abusque', 'adaeque', 'adusque', 'denique', 'deque', 'susque', 'oblique', 'peraeque', 'plenisque', 'quandoque', 'quisque', 'quaeque', 'cuiusque', 'cuique', 'quemque', 'quamque', 'quaque', 'quique', 'quorumque', 'quarumque', 'quibusque', 'quosque', 'quasque', 'quotusquisque', 'quousque', 'ubique', 'undique', 'usque', 'uterque', 'utique', 'utroque', 'utribique', 'torque', 'coque', 'concoque', 'contorque', 'detorque', 'decoque', 'excoque', 'extorque', 'obtorque', 'optorque', 'retorque', 'recoque', 'attorque', 'incoque', 'intorque', 'praetorque'] if word not in que_pass_list: word = re.sub(r'que$', '', word) else: in_que_pass_list = True return word, in_que_pass_list
[ "def", "_checkremove_que", "(", "self", ",", "word", ")", ":", "in_que_pass_list", "=", "False", "que_pass_list", "=", "[", "'atque'", ",", "'quoque'", ",", "'neque'", ",", "'itaque'", ",", "'absque'", ",", "'apsque'", ",", "'abusque'", ",", "'adaeque'", ","...
If word ends in -que and if word is not in pass list, strip -que
[ "If", "word", "ends", "in", "-", "que", "and", "if", "word", "is", "not", "in", "pass", "list", "strip", "-", "que" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/stem/latin/stem.py#L49-L114
230,483
cltk/cltk
cltk/stem/latin/stem.py
Stemmer._matchremove_simple_endings
def _matchremove_simple_endings(self, word): """Remove the noun, adjective, adverb word endings""" was_stemmed = False # noun, adjective, and adverb word endings sorted by charlen, then alph simple_endings = ['ibus', 'ius', 'ae', 'am', 'as', 'em', 'es', 'ia', 'is', 'nt', 'os', 'ud', 'um', 'us', 'a', 'e', 'i', 'o', 'u'] for ending in simple_endings: if word.endswith(ending): word = re.sub(r'{0}$'.format(ending), '', word) was_stemmed = True break return word, was_stemmed
python
def _matchremove_simple_endings(self, word): was_stemmed = False # noun, adjective, and adverb word endings sorted by charlen, then alph simple_endings = ['ibus', 'ius', 'ae', 'am', 'as', 'em', 'es', 'ia', 'is', 'nt', 'os', 'ud', 'um', 'us', 'a', 'e', 'i', 'o', 'u'] for ending in simple_endings: if word.endswith(ending): word = re.sub(r'{0}$'.format(ending), '', word) was_stemmed = True break return word, was_stemmed
[ "def", "_matchremove_simple_endings", "(", "self", ",", "word", ")", ":", "was_stemmed", "=", "False", "# noun, adjective, and adverb word endings sorted by charlen, then alph", "simple_endings", "=", "[", "'ibus'", ",", "'ius'", ",", "'ae'", ",", "'am'", ",", "'as'", ...
Remove the noun, adjective, adverb word endings
[ "Remove", "the", "noun", "adjective", "adverb", "word", "endings" ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/stem/latin/stem.py#L116-L148
230,484
cltk/cltk
cltk/prosody/latin/syllabifier.py
Syllabifier._setup
def _setup(self, word) -> List[str]: """ Prepares a word for syllable processing. If the word starts with a prefix, process it separately. :param word: :return: """ if len(word) == 1: return [word] for prefix in self.constants.PREFIXES: if word.startswith(prefix): (first, rest) = string_utils.split_on(word, prefix) if self._contains_vowels(rest): return string_utils.remove_blank_spaces( self._process(first) + self._process(rest)) # a word like pror can happen from ellision return string_utils.remove_blank_spaces(self._process(word)) if word in self.constants.UI_EXCEPTIONS.keys(): return self.constants.UI_EXCEPTIONS[word] return string_utils.remove_blank_spaces(self._process(word))
python
def _setup(self, word) -> List[str]: if len(word) == 1: return [word] for prefix in self.constants.PREFIXES: if word.startswith(prefix): (first, rest) = string_utils.split_on(word, prefix) if self._contains_vowels(rest): return string_utils.remove_blank_spaces( self._process(first) + self._process(rest)) # a word like pror can happen from ellision return string_utils.remove_blank_spaces(self._process(word)) if word in self.constants.UI_EXCEPTIONS.keys(): return self.constants.UI_EXCEPTIONS[word] return string_utils.remove_blank_spaces(self._process(word))
[ "def", "_setup", "(", "self", ",", "word", ")", "->", "List", "[", "str", "]", ":", "if", "len", "(", "word", ")", "==", "1", ":", "return", "[", "word", "]", "for", "prefix", "in", "self", ".", "constants", ".", "PREFIXES", ":", "if", "word", ...
Prepares a word for syllable processing. If the word starts with a prefix, process it separately. :param word: :return:
[ "Prepares", "a", "word", "for", "syllable", "processing", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/syllabifier.py#L168-L188
230,485
cltk/cltk
cltk/prosody/latin/syllabifier.py
Syllabifier.convert_consonantal_i
def convert_consonantal_i(self, word) -> str: """Convert i to j when at the start of a word.""" match = list(self.consonantal_i_matcher.finditer(word)) if match: if word[0].isupper(): return "J" + word[1:] return "j" + word[1:] return word
python
def convert_consonantal_i(self, word) -> str: match = list(self.consonantal_i_matcher.finditer(word)) if match: if word[0].isupper(): return "J" + word[1:] return "j" + word[1:] return word
[ "def", "convert_consonantal_i", "(", "self", ",", "word", ")", "->", "str", ":", "match", "=", "list", "(", "self", ".", "consonantal_i_matcher", ".", "finditer", "(", "word", ")", ")", "if", "match", ":", "if", "word", "[", "0", "]", ".", "isupper", ...
Convert i to j when at the start of a word.
[ "Convert", "i", "to", "j", "when", "at", "the", "start", "of", "a", "word", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/syllabifier.py#L190-L197
230,486
cltk/cltk
cltk/prosody/latin/syllabifier.py
Syllabifier._process
def _process(self, word: str) -> List[str]: """ Process a word into a list of strings representing the syllables of the word. This method describes rules for consonant grouping behaviors and then iteratively applies those rules the list of letters that comprise the word, until all the letters are grouped into appropriate syllable groups. :param word: :return: """ # if a blank arrives from splitting, just return an empty list if len(word.strip()) == 0: return [] word = self.convert_consonantal_i(word) my_word = " " + word + " " letters = list(my_word) positions = [] for dipth in self.diphthongs: if dipth in my_word: dipth_matcher = re.compile("{}".format(dipth)) matches = dipth_matcher.finditer(my_word) for match in matches: (start, end) = match.span() positions.append(start) matches = self.kw_matcher.finditer(my_word) for match in matches: (start, end) = match.span() positions.append(start) letters = string_utils.merge_next(letters, positions) letters = string_utils.remove_blanks(letters) positions.clear() if not self._contains_vowels("".join(letters)): return ["".join(letters).strip()] # occurs when only 'qu' appears by ellision positions = self._starting_consonants_only(letters) while len(positions) > 0: letters = string_utils.move_consonant_right(letters, positions) letters = string_utils.remove_blanks(letters) positions = self._starting_consonants_only(letters) positions = self._ending_consonants_only(letters) while len(positions) > 0: letters = string_utils.move_consonant_left(letters, positions) letters = string_utils.remove_blanks(letters) positions = self._ending_consonants_only(letters) positions = self._find_solo_consonant(letters) while len(positions) > 0: letters = self._move_consonant(letters, positions) letters = string_utils.remove_blanks(letters) positions = self._find_solo_consonant(letters) positions = self._find_consonant_cluster(letters) while len(positions) > 0: letters = self._move_consonant(letters, positions) letters = string_utils.remove_blanks(letters) positions = self._find_consonant_cluster(letters) return letters
python
def _process(self, word: str) -> List[str]: # if a blank arrives from splitting, just return an empty list if len(word.strip()) == 0: return [] word = self.convert_consonantal_i(word) my_word = " " + word + " " letters = list(my_word) positions = [] for dipth in self.diphthongs: if dipth in my_word: dipth_matcher = re.compile("{}".format(dipth)) matches = dipth_matcher.finditer(my_word) for match in matches: (start, end) = match.span() positions.append(start) matches = self.kw_matcher.finditer(my_word) for match in matches: (start, end) = match.span() positions.append(start) letters = string_utils.merge_next(letters, positions) letters = string_utils.remove_blanks(letters) positions.clear() if not self._contains_vowels("".join(letters)): return ["".join(letters).strip()] # occurs when only 'qu' appears by ellision positions = self._starting_consonants_only(letters) while len(positions) > 0: letters = string_utils.move_consonant_right(letters, positions) letters = string_utils.remove_blanks(letters) positions = self._starting_consonants_only(letters) positions = self._ending_consonants_only(letters) while len(positions) > 0: letters = string_utils.move_consonant_left(letters, positions) letters = string_utils.remove_blanks(letters) positions = self._ending_consonants_only(letters) positions = self._find_solo_consonant(letters) while len(positions) > 0: letters = self._move_consonant(letters, positions) letters = string_utils.remove_blanks(letters) positions = self._find_solo_consonant(letters) positions = self._find_consonant_cluster(letters) while len(positions) > 0: letters = self._move_consonant(letters, positions) letters = string_utils.remove_blanks(letters) positions = self._find_consonant_cluster(letters) return letters
[ "def", "_process", "(", "self", ",", "word", ":", "str", ")", "->", "List", "[", "str", "]", ":", "# if a blank arrives from splitting, just return an empty list", "if", "len", "(", "word", ".", "strip", "(", ")", ")", "==", "0", ":", "return", "[", "]",...
Process a word into a list of strings representing the syllables of the word. This method describes rules for consonant grouping behaviors and then iteratively applies those rules the list of letters that comprise the word, until all the letters are grouped into appropriate syllable groups. :param word: :return:
[ "Process", "a", "word", "into", "a", "list", "of", "strings", "representing", "the", "syllables", "of", "the", "word", ".", "This", "method", "describes", "rules", "for", "consonant", "grouping", "behaviors", "and", "then", "iteratively", "applies", "those", "...
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/syllabifier.py#L199-L252
230,487
cltk/cltk
cltk/prosody/latin/syllabifier.py
Syllabifier._ends_with_vowel
def _ends_with_vowel(self, letter_group: str) -> bool: """Check if a string ends with a vowel.""" if len(letter_group) == 0: return False return self._contains_vowels(letter_group[-1])
python
def _ends_with_vowel(self, letter_group: str) -> bool: if len(letter_group) == 0: return False return self._contains_vowels(letter_group[-1])
[ "def", "_ends_with_vowel", "(", "self", ",", "letter_group", ":", "str", ")", "->", "bool", ":", "if", "len", "(", "letter_group", ")", "==", "0", ":", "return", "False", "return", "self", ".", "_contains_vowels", "(", "letter_group", "[", "-", "1", "]",...
Check if a string ends with a vowel.
[ "Check", "if", "a", "string", "ends", "with", "a", "vowel", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/syllabifier.py#L262-L266
230,488
cltk/cltk
cltk/prosody/latin/syllabifier.py
Syllabifier._starts_with_vowel
def _starts_with_vowel(self, letter_group: str) -> bool: """Check if a string starts with a vowel.""" if len(letter_group) == 0: return False return self._contains_vowels(letter_group[0])
python
def _starts_with_vowel(self, letter_group: str) -> bool: if len(letter_group) == 0: return False return self._contains_vowels(letter_group[0])
[ "def", "_starts_with_vowel", "(", "self", ",", "letter_group", ":", "str", ")", "->", "bool", ":", "if", "len", "(", "letter_group", ")", "==", "0", ":", "return", "False", "return", "self", ".", "_contains_vowels", "(", "letter_group", "[", "0", "]", ")...
Check if a string starts with a vowel.
[ "Check", "if", "a", "string", "starts", "with", "a", "vowel", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/syllabifier.py#L268-L272
230,489
cltk/cltk
cltk/prosody/latin/syllabifier.py
Syllabifier._starting_consonants_only
def _starting_consonants_only(self, letters: list) -> list: """Return a list of starting consonant positions.""" for idx, letter in enumerate(letters): if not self._contains_vowels(letter) and self._contains_consonants(letter): return [idx] if self._contains_vowels(letter): return [] if self._contains_vowels(letter) and self._contains_consonants(letter): return [] return []
python
def _starting_consonants_only(self, letters: list) -> list: for idx, letter in enumerate(letters): if not self._contains_vowels(letter) and self._contains_consonants(letter): return [idx] if self._contains_vowels(letter): return [] if self._contains_vowels(letter) and self._contains_consonants(letter): return [] return []
[ "def", "_starting_consonants_only", "(", "self", ",", "letters", ":", "list", ")", "->", "list", ":", "for", "idx", ",", "letter", "in", "enumerate", "(", "letters", ")", ":", "if", "not", "self", ".", "_contains_vowels", "(", "letter", ")", "and", "self...
Return a list of starting consonant positions.
[ "Return", "a", "list", "of", "starting", "consonant", "positions", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/syllabifier.py#L274-L283
230,490
cltk/cltk
cltk/prosody/latin/syllabifier.py
Syllabifier._ending_consonants_only
def _ending_consonants_only(self, letters: List[str]) -> List[int]: """Return a list of positions for ending consonants.""" reversed_letters = list(reversed(letters)) length = len(letters) for idx, letter in enumerate(reversed_letters): if not self._contains_vowels(letter) and self._contains_consonants(letter): return [(length - idx) - 1] if self._contains_vowels(letter): return [] if self._contains_vowels(letter) and self._contains_consonants(letter): return [] return []
python
def _ending_consonants_only(self, letters: List[str]) -> List[int]: reversed_letters = list(reversed(letters)) length = len(letters) for idx, letter in enumerate(reversed_letters): if not self._contains_vowels(letter) and self._contains_consonants(letter): return [(length - idx) - 1] if self._contains_vowels(letter): return [] if self._contains_vowels(letter) and self._contains_consonants(letter): return [] return []
[ "def", "_ending_consonants_only", "(", "self", ",", "letters", ":", "List", "[", "str", "]", ")", "->", "List", "[", "int", "]", ":", "reversed_letters", "=", "list", "(", "reversed", "(", "letters", ")", ")", "length", "=", "len", "(", "letters", ")",...
Return a list of positions for ending consonants.
[ "Return", "a", "list", "of", "positions", "for", "ending", "consonants", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/syllabifier.py#L285-L296
230,491
cltk/cltk
cltk/prosody/latin/syllabifier.py
Syllabifier._find_solo_consonant
def _find_solo_consonant(self, letters: List[str]) -> List[int]: """Find the positions of any solo consonants that are not yet paired with a vowel.""" solos = [] for idx, letter in enumerate(letters): if len(letter) == 1 and self._contains_consonants(letter): solos.append(idx) return solos
python
def _find_solo_consonant(self, letters: List[str]) -> List[int]: solos = [] for idx, letter in enumerate(letters): if len(letter) == 1 and self._contains_consonants(letter): solos.append(idx) return solos
[ "def", "_find_solo_consonant", "(", "self", ",", "letters", ":", "List", "[", "str", "]", ")", "->", "List", "[", "int", "]", ":", "solos", "=", "[", "]", "for", "idx", ",", "letter", "in", "enumerate", "(", "letters", ")", ":", "if", "len", "(", ...
Find the positions of any solo consonants that are not yet paired with a vowel.
[ "Find", "the", "positions", "of", "any", "solo", "consonants", "that", "are", "not", "yet", "paired", "with", "a", "vowel", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/syllabifier.py#L298-L304
230,492
cltk/cltk
cltk/prosody/latin/syllabifier.py
Syllabifier._move_consonant
def _move_consonant(self, letters: list, positions: List[int]) -> List[str]: """ Given a list of consonant positions, move the consonants according to certain consonant syllable behavioral rules for gathering and grouping. :param letters: :param positions: :return: """ for pos in positions: previous_letter = letters[pos - 1] consonant = letters[pos] next_letter = letters[pos + 1] if self._contains_vowels(next_letter) and self._starts_with_vowel(next_letter): return string_utils.move_consonant_right(letters, [pos]) if self._contains_vowels(previous_letter) and self._ends_with_vowel( previous_letter) and len(previous_letter) == 1: return string_utils.move_consonant_left(letters, [pos]) if previous_letter + consonant in self.constants.ASPIRATES: return string_utils.move_consonant_left(letters, [pos]) if consonant + next_letter in self.constants.ASPIRATES: return string_utils.move_consonant_right(letters, [pos]) if next_letter[0] == consonant: return string_utils.move_consonant_left(letters, [pos]) if consonant in self.constants.MUTES and next_letter[0] in self.constants.LIQUIDS: return string_utils.move_consonant_right(letters, [pos]) if consonant in ['k', 'K'] and next_letter[0] in ['w', 'W']: return string_utils.move_consonant_right(letters, [pos]) if self._contains_consonants(next_letter[0]) and self._starts_with_vowel( previous_letter[-1]): return string_utils.move_consonant_left(letters, [pos]) # fall through case if self._contains_consonants(next_letter[0]): return string_utils.move_consonant_right(letters, [pos]) return letters
python
def _move_consonant(self, letters: list, positions: List[int]) -> List[str]: for pos in positions: previous_letter = letters[pos - 1] consonant = letters[pos] next_letter = letters[pos + 1] if self._contains_vowels(next_letter) and self._starts_with_vowel(next_letter): return string_utils.move_consonant_right(letters, [pos]) if self._contains_vowels(previous_letter) and self._ends_with_vowel( previous_letter) and len(previous_letter) == 1: return string_utils.move_consonant_left(letters, [pos]) if previous_letter + consonant in self.constants.ASPIRATES: return string_utils.move_consonant_left(letters, [pos]) if consonant + next_letter in self.constants.ASPIRATES: return string_utils.move_consonant_right(letters, [pos]) if next_letter[0] == consonant: return string_utils.move_consonant_left(letters, [pos]) if consonant in self.constants.MUTES and next_letter[0] in self.constants.LIQUIDS: return string_utils.move_consonant_right(letters, [pos]) if consonant in ['k', 'K'] and next_letter[0] in ['w', 'W']: return string_utils.move_consonant_right(letters, [pos]) if self._contains_consonants(next_letter[0]) and self._starts_with_vowel( previous_letter[-1]): return string_utils.move_consonant_left(letters, [pos]) # fall through case if self._contains_consonants(next_letter[0]): return string_utils.move_consonant_right(letters, [pos]) return letters
[ "def", "_move_consonant", "(", "self", ",", "letters", ":", "list", ",", "positions", ":", "List", "[", "int", "]", ")", "->", "List", "[", "str", "]", ":", "for", "pos", "in", "positions", ":", "previous_letter", "=", "letters", "[", "pos", "-", "1"...
Given a list of consonant positions, move the consonants according to certain consonant syllable behavioral rules for gathering and grouping. :param letters: :param positions: :return:
[ "Given", "a", "list", "of", "consonant", "positions", "move", "the", "consonants", "according", "to", "certain", "consonant", "syllable", "behavioral", "rules", "for", "gathering", "and", "grouping", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/syllabifier.py#L317-L351
230,493
cltk/cltk
cltk/prosody/latin/syllabifier.py
Syllabifier.get_syllable_count
def get_syllable_count(self, syllables: List[str]) -> int: """ Counts the number of syllable groups that would occur after ellision. Often we will want preserve the position and separation of syllables so that they can be used to reconstitute a line, and apply stresses to the original word positions. However, we also want to be able to count the number of syllables accurately. :param syllables: :return: >>> syllabifier = Syllabifier() >>> print(syllabifier.get_syllable_count([ ... 'Jām', 'tūm', 'c', 'au', 'sus', 'es', 'u', 'nus', 'I', 'ta', 'lo', 'rum'])) 11 """ tmp_syllables = copy.deepcopy(syllables) return len(string_utils.remove_blank_spaces( string_utils.move_consonant_right(tmp_syllables, self._find_solo_consonant(tmp_syllables))))
python
def get_syllable_count(self, syllables: List[str]) -> int: tmp_syllables = copy.deepcopy(syllables) return len(string_utils.remove_blank_spaces( string_utils.move_consonant_right(tmp_syllables, self._find_solo_consonant(tmp_syllables))))
[ "def", "get_syllable_count", "(", "self", ",", "syllables", ":", "List", "[", "str", "]", ")", "->", "int", ":", "tmp_syllables", "=", "copy", ".", "deepcopy", "(", "syllables", ")", "return", "len", "(", "string_utils", ".", "remove_blank_spaces", "(", "s...
Counts the number of syllable groups that would occur after ellision. Often we will want preserve the position and separation of syllables so that they can be used to reconstitute a line, and apply stresses to the original word positions. However, we also want to be able to count the number of syllables accurately. :param syllables: :return: >>> syllabifier = Syllabifier() >>> print(syllabifier.get_syllable_count([ ... 'Jām', 'tūm', 'c', 'au', 'sus', 'es', 'u', 'nus', 'I', 'ta', 'lo', 'rum'])) 11
[ "Counts", "the", "number", "of", "syllable", "groups", "that", "would", "occur", "after", "ellision", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/syllabifier.py#L353-L372
230,494
cltk/cltk
cltk/corpus/sanskrit/itrans/itrans_transliterator.py
_unrecognised
def _unrecognised(achr): """ Handle unrecognised characters. """ if options['handleUnrecognised'] == UNRECOGNISED_ECHO: return achr elif options['handleUnrecognised'] == UNRECOGNISED_SUBSTITUTE: return options['substituteChar'] else: raise KeyError(achr)
python
def _unrecognised(achr): if options['handleUnrecognised'] == UNRECOGNISED_ECHO: return achr elif options['handleUnrecognised'] == UNRECOGNISED_SUBSTITUTE: return options['substituteChar'] else: raise KeyError(achr)
[ "def", "_unrecognised", "(", "achr", ")", ":", "if", "options", "[", "'handleUnrecognised'", "]", "==", "UNRECOGNISED_ECHO", ":", "return", "achr", "elif", "options", "[", "'handleUnrecognised'", "]", "==", "UNRECOGNISED_SUBSTITUTE", ":", "return", "options", "[",...
Handle unrecognised characters.
[ "Handle", "unrecognised", "characters", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/sanskrit/itrans/itrans_transliterator.py#L139-L146
230,495
cltk/cltk
cltk/corpus/sanskrit/itrans/itrans_transliterator.py
CharacterBlock._transliterate
def _transliterate (self, text, outFormat): """ Transliterate the text to the target transliteration scheme.""" result = [] for c in text: if c.isspace(): result.append(c) try: result.append(self[c].equivalents[outFormat.name]) except KeyError: result.append(_unrecognised(c)) return result
python
def _transliterate (self, text, outFormat): result = [] for c in text: if c.isspace(): result.append(c) try: result.append(self[c].equivalents[outFormat.name]) except KeyError: result.append(_unrecognised(c)) return result
[ "def", "_transliterate", "(", "self", ",", "text", ",", "outFormat", ")", ":", "result", "=", "[", "]", "for", "c", "in", "text", ":", "if", "c", ".", "isspace", "(", ")", ":", "result", ".", "append", "(", "c", ")", "try", ":", "result", ".", ...
Transliterate the text to the target transliteration scheme.
[ "Transliterate", "the", "text", "to", "the", "target", "transliteration", "scheme", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/sanskrit/itrans/itrans_transliterator.py#L247-L256
230,496
cltk/cltk
cltk/corpus/sanskrit/itrans/itrans_transliterator.py
TransliterationScheme._setupParseTree
def _setupParseTree(self, rowFrom, rowTo, colIndex, tree): """ Build the search tree for multi-character encodings. """ if colIndex == self._longestEntry: return prevchar = None rowIndex = rowFrom while rowIndex <= rowTo: if colIndex < len(self._parsedata[rowIndex]): c = self._parsedata[rowIndex][colIndex] if c != prevchar: tree[c] = {} if prevchar is not None: self._setupParseTree(rowFrom, rowIndex - 1, colIndex + 1, tree[prevchar]) rowFrom = rowIndex prevchar = c if rowIndex == rowTo: self._setupParseTree(rowFrom, rowIndex, colIndex + 1, tree[prevchar]) rowIndex = rowIndex + 1
python
def _setupParseTree(self, rowFrom, rowTo, colIndex, tree): if colIndex == self._longestEntry: return prevchar = None rowIndex = rowFrom while rowIndex <= rowTo: if colIndex < len(self._parsedata[rowIndex]): c = self._parsedata[rowIndex][colIndex] if c != prevchar: tree[c] = {} if prevchar is not None: self._setupParseTree(rowFrom, rowIndex - 1, colIndex + 1, tree[prevchar]) rowFrom = rowIndex prevchar = c if rowIndex == rowTo: self._setupParseTree(rowFrom, rowIndex, colIndex + 1, tree[prevchar]) rowIndex = rowIndex + 1
[ "def", "_setupParseTree", "(", "self", ",", "rowFrom", ",", "rowTo", ",", "colIndex", ",", "tree", ")", ":", "if", "colIndex", "==", "self", ".", "_longestEntry", ":", "return", "prevchar", "=", "None", "rowIndex", "=", "rowFrom", "while", "rowIndex", "<="...
Build the search tree for multi-character encodings.
[ "Build", "the", "search", "tree", "for", "multi", "-", "character", "encodings", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/sanskrit/itrans/itrans_transliterator.py#L322-L340
230,497
cltk/cltk
cltk/corpus/sanskrit/itrans/itrans_transliterator.py
TransliterationScheme._transliterate
def _transliterate (self, text, outFormat): """ Transliterate the text to Unicode.""" result = [] text = self._preprocess(text) i = 0 while i < len(text): if text[i].isspace(): result.append(text[i]) i = i+1 else: chr = self._getNextChar(text, i) try: result.append(self[chr].unichr) except KeyError: result.append(_unrecognised(chr)) i = i + len(chr) return result
python
def _transliterate (self, text, outFormat): result = [] text = self._preprocess(text) i = 0 while i < len(text): if text[i].isspace(): result.append(text[i]) i = i+1 else: chr = self._getNextChar(text, i) try: result.append(self[chr].unichr) except KeyError: result.append(_unrecognised(chr)) i = i + len(chr) return result
[ "def", "_transliterate", "(", "self", ",", "text", ",", "outFormat", ")", ":", "result", "=", "[", "]", "text", "=", "self", ".", "_preprocess", "(", "text", ")", "i", "=", "0", "while", "i", "<", "len", "(", "text", ")", ":", "if", "text", "[", ...
Transliterate the text to Unicode.
[ "Transliterate", "the", "text", "to", "Unicode", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/sanskrit/itrans/itrans_transliterator.py#L369-L385
230,498
cltk/cltk
cltk/corpus/sanskrit/itrans/itrans_transliterator.py
DevanagariTransliterationScheme._equivalent
def _equivalent(self, char, prev, next, implicitA): """ Transliterate a Devanagari character to Latin. Add implicit As unless overridden by VIRAMA. """ result = [] if char.unichr != DevanagariCharacter._VIRAMA: result.append(char.equivalents[self.name]) """ Append implicit A to consonants if the next character isn't a vowel. """ if implicitA and char.isConsonant \ and ((next is not None \ and next.unichr != DevanagariCharacter._VIRAMA \ and not next.isVowel) \ or next is None): result.append(characterBlocks['DEVANAGARI']\ [DevanagariCharacter._LETTER_A].equivalents[self.name]) return result
python
def _equivalent(self, char, prev, next, implicitA): result = [] if char.unichr != DevanagariCharacter._VIRAMA: result.append(char.equivalents[self.name]) """ Append implicit A to consonants if the next character isn't a vowel. """ if implicitA and char.isConsonant \ and ((next is not None \ and next.unichr != DevanagariCharacter._VIRAMA \ and not next.isVowel) \ or next is None): result.append(characterBlocks['DEVANAGARI']\ [DevanagariCharacter._LETTER_A].equivalents[self.name]) return result
[ "def", "_equivalent", "(", "self", ",", "char", ",", "prev", ",", "next", ",", "implicitA", ")", ":", "result", "=", "[", "]", "if", "char", ".", "unichr", "!=", "DevanagariCharacter", ".", "_VIRAMA", ":", "result", ".", "append", "(", "char", ".", "...
Transliterate a Devanagari character to Latin. Add implicit As unless overridden by VIRAMA.
[ "Transliterate", "a", "Devanagari", "character", "to", "Latin", ".", "Add", "implicit", "As", "unless", "overridden", "by", "VIRAMA", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/sanskrit/itrans/itrans_transliterator.py#L668-L685
230,499
cltk/cltk
cltk/corpus/utils/importer.py
CorpusImporter.list_corpora
def list_corpora(self): """Show corpora available for the CLTK to download.""" try: # corpora = LANGUAGE_CORPORA[self.language] corpora = self.all_corpora corpus_names = [corpus['name'] for corpus in corpora] return corpus_names except (NameError, KeyError) as error: msg = 'Corpus not available for language "{}": {}'.format(self.language, error) logger.error(msg) raise CorpusImportError(msg)
python
def list_corpora(self): try: # corpora = LANGUAGE_CORPORA[self.language] corpora = self.all_corpora corpus_names = [corpus['name'] for corpus in corpora] return corpus_names except (NameError, KeyError) as error: msg = 'Corpus not available for language "{}": {}'.format(self.language, error) logger.error(msg) raise CorpusImportError(msg)
[ "def", "list_corpora", "(", "self", ")", ":", "try", ":", "# corpora = LANGUAGE_CORPORA[self.language]", "corpora", "=", "self", ".", "all_corpora", "corpus_names", "=", "[", "corpus", "[", "'name'", "]", "for", "corpus", "in", "corpora", "]", "return", "corpus_...
Show corpora available for the CLTK to download.
[ "Show", "corpora", "available", "for", "the", "CLTK", "to", "download", "." ]
ed9c025b7ec43c949481173251b70e05e4dffd27
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/utils/importer.py#L197-L207