_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q34200
LemmaReplacer._load_entries
train
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(r...
python
{ "resource": "" }
q34201
LemmaReplacer.lemmatize
train
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 matc...
python
{ "resource": "" }
q34202
BaseSentenceTokenizer.tokenize
train
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: t...
python
{ "resource": "" }
q34203
BaseRegexSentenceTokenizer.tokenize
train
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
{ "resource": "" }
q34204
OldEnglishDictionaryLemmatizer._load_forms_and_lemmas
train
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', ...
python
{ "resource": "" }
q34205
OldEnglishDictionaryLemmatizer._load_type_counts
train
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...
python
{ "resource": "" }
q34206
OldEnglishDictionaryLemmatizer._relative_frequency
train
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
{ "resource": "" }
q34207
OldEnglishDictionaryLemmatizer._lemmatize_token
train
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 ...
python
{ "resource": "" }
q34208
OldEnglishDictionaryLemmatizer.lemmatize
train
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 isinstanc...
python
{ "resource": "" }
q34209
OldEnglishDictionaryLemmatizer.evaluate
train
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]',...
python
{ "resource": "" }
q34210
Stemmer.get_stem
train
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']['s...
python
{ "resource": "" }
q34211
Macronizer._retrieve_tag
train
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_backof...
python
{ "resource": "" }
q34212
Macronizer._retrieve_morpheus_entry
train
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....
python
{ "resource": "" }
q34213
Macronizer._macronize_word
train
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 {} c...
python
{ "resource": "" }
q34214
Macronizer.macronize_tags
train
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')...
python
{ "resource": "" }
q34215
Macronizer.macronize_text
train
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] f...
python
{ "resource": "" }
q34216
Tokenizer.string_tokenizer
train
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}iszk...
python
{ "resource": "" }
q34217
Tokenizer.line_tokenizer
train
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', ...
python
{ "resource": "" }
q34218
Syllabifier.get_lang_data
train
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_...
python
{ "resource": "" }
q34219
Syllabifier.orthographic_syllabify
train
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(wo...
python
{ "resource": "" }
q34220
read_file
train
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
{ "resource": "" }
q34221
ConcordanceIndex.return_concordance_all
train
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 =...
python
{ "resource": "" }
q34222
ScansionFormatter.hexameter
train
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--")) -...
python
{ "resource": "" }
q34223
ScansionFormatter.merge_line_scansion
train
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 appl...
python
{ "resource": "" }
q34224
arabicrange
train
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
{ "resource": "" }
q34225
is_vocalized
train
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: ...
python
{ "resource": "" }
q34226
is_arabicstring
train
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...
python
{ "resource": "" }
q34227
is_arabicword
train
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: Bool...
python
{ "resource": "" }
q34228
normalize_hamza
train
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_MAD...
python
{ "resource": "" }
q34229
joint
train
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 o...
python
{ "resource": "" }
q34230
shaddalike
train
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 vocaliz...
python
{ "resource": "" }
q34231
reduce_tashkeel
train
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))...
python
{ "resource": "" }
q34232
vocalized_similarity
train
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 @re...
python
{ "resource": "" }
q34233
tokenize
train
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...
python
{ "resource": "" }
q34234
gen_docs
train
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_au...
python
{ "resource": "" }
q34235
make_model
train
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) # se...
python
{ "resource": "" }
q34236
get_sims
train
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 casefo...
python
{ "resource": "" }
q34237
HexameterScanner.invalid_foot_to_spondee
train
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 ...
python
{ "resource": "" }
q34238
HexameterScanner.correct_dactyl_chain
train
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...
python
{ "resource": "" }
q34239
apply_raw_r_assimilation
train
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_assim...
python
{ "resource": "" }
q34240
add_r_ending_to_syllable
train
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...
python
{ "resource": "" }
q34241
add_r_ending
train
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('m...
python
{ "resource": "" }
q34242
apply_i_umlaut
train
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ð") ...
python
{ "resource": "" }
q34243
HendecasyllableScanner.correct_invalid_start
train
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( ...
python
{ "resource": "" }
q34244
SequentialBackoffLemmatizer.tag_one
train
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 ...
python
{ "resource": "" }
q34245
tokenize_akkadian_words
train
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) """...
python
{ "resource": "" }
q34246
tokenize_arabic_words
train
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.to...
python
{ "resource": "" }
q34247
tokenize_middle_high_german_words
train
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'(?<=...
python
{ "resource": "" }
q34248
WordTokenizer.tokenize
train
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 = tokeni...
python
{ "resource": "" }
q34249
WordTokenizer.tokenize_sign
train
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
{ "resource": "" }
q34250
TLGU._check_import_source
train
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') ...
python
{ "resource": "" }
q34251
TLGU._check_install
train
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_...
python
{ "resource": "" }
q34252
Syllabifier.syllabify
train
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 dict...
python
{ "resource": "" }
q34253
Scansion._clean_text
train
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: ...
python
{ "resource": "" }
q34254
Scansion._tokenize
train
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....
python
{ "resource": "" }
q34255
Scansion._long_by_nature
train
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 """ ...
python
{ "resource": "" }
q34256
Scansion._long_by_position
train
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) S...
python
{ "resource": "" }
q34257
Scansion.scan_text
train
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(syllabl...
python
{ "resource": "" }
q34258
Stemmer.stem
train
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_li...
python
{ "resource": "" }
q34259
Stemmer._checkremove_que
train
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', ...
python
{ "resource": "" }
q34260
Stemmer._matchremove_simple_endings
train
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', ...
python
{ "resource": "" }
q34261
Syllabifier._setup
train
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: ...
python
{ "resource": "" }
q34262
Syllabifier.convert_consonantal_i
train
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
{ "resource": "" }
q34263
Syllabifier._process
train
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 le...
python
{ "resource": "" }
q34264
Syllabifier._ends_with_vowel
train
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
{ "resource": "" }
q34265
Syllabifier._starts_with_vowel
train
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
{ "resource": "" }
q34266
Syllabifier._starting_consonants_only
train
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_vowel...
python
{ "resource": "" }
q34267
Syllabifier._ending_consonants_only
train
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) an...
python
{ "resource": "" }
q34268
Syllabifier._find_solo_consonant
train
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.ap...
python
{ "resource": "" }
q34269
Syllabifier._move_consonant
train
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: ...
python
{ "resource": "" }
q34270
Syllabifier.get_syllable_count
train
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 w...
python
{ "resource": "" }
q34271
_unrecognised
train
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
{ "resource": "" }
q34272
CharacterBlock._transliterate
train
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...
python
{ "resource": "" }
q34273
TransliterationScheme._setupParseTree
train
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._pa...
python
{ "resource": "" }
q34274
TransliterationScheme._transliterate
train
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: ...
python
{ "resource": "" }
q34275
DevanagariTransliterationScheme._equivalent
train
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.nam...
python
{ "resource": "" }
q34276
CorpusImporter.list_corpora
train
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, ...
python
{ "resource": "" }
q34277
onekgreek_tei_xml_to_text
train
def onekgreek_tei_xml_to_text(): """Find TEI XML dir of TEI XML for the First 1k Years of Greek corpus.""" if not bs4_installed: logger.error('Install `bs4` and `lxml` to parse these TEI files.') raise ImportError xml_dir = os.path.expanduser('~/cltk_data/greek/text/greek_text_first1kgreek/d...
python
{ "resource": "" }
q34278
onekgreek_tei_xml_to_text_capitains
train
def onekgreek_tei_xml_to_text_capitains(): """Use MyCapitains program to convert TEI to plaintext.""" file = os.path.expanduser( '~/cltk_data/greek/text/greek_text_first1kgreek/data/tlg0627/tlg021/tlg0627.tlg021.1st1K-grc1.xml') xml_dir = os.path.expanduser('~/cltk_data/greek/text/greek_text_first1k...
python
{ "resource": "" }
q34279
Lemmata.load_replacement_patterns
train
def load_replacement_patterns(self): """Check for availability of the specified dictionary.""" filename = self.dictionary + '.py' models = self.language + '_models_cltk' rel_path = os.path.join('~/cltk_data', self.language, ...
python
{ "resource": "" }
q34280
Lemmata.lookup
train
def lookup(self, tokens): """Return a list of possible lemmata and their probabilities for each token""" lemmatized_tokens = [] if type(tokens) == list: for token in tokens: # look for token in lemma dict keys if token.lower() in self.lemmata.keys(): ...
python
{ "resource": "" }
q34281
Lemmata.isolate
train
def isolate(obj): """Feed a standard semantic object in and receive a simple list of lemmata """ answers = [] for token in obj: lemmata = token[1] for pair in lemmata: answers.append(pair[0]) return answers
python
{ "resource": "" }
q34282
Syllabifier.set_hierarchy
train
def set_hierarchy(self, hierarchy): """ Sets an alternative sonority hierarchy, note that you will also need to specify the vowelset with the set_vowels, in order for the module to correctly identify each nucleus. The order of the phonemes defined is by decreased consonantality ...
python
{ "resource": "" }
q34283
Syllabifier.syllabify_ssp
train
def syllabify_ssp(self, word): """ Syllabifies a word according to the Sonority Sequencing Principle :param word: Word to be syllabified :return: List consisting of syllables Example: First you need to define the matters of articulation >>> high_vowels =...
python
{ "resource": "" }
q34284
PentameterScanner.make_spondaic
train
def make_spondaic(self, scansion: str) -> str: """ If a pentameter line has 12 syllables, then it must start with double spondees. :param scansion: a string of scansion patterns :return: a scansion pattern string starting with two spondees >>> print(PentameterScanner().make_spo...
python
{ "resource": "" }
q34285
PentameterScanner.correct_penultimate_dactyl_chain
train
def correct_penultimate_dactyl_chain(self, scansion: str) -> str: """ For pentameter the last two feet of the verse are predictable dactyls, and do not regularly allow substitutions. :param scansion: scansion line thus far :return: corrected line of scansion >>> print(P...
python
{ "resource": "" }
q34286
eval_str_to_list
train
def eval_str_to_list(input_str: str) -> List[str]: """Turn str into str or tuple.""" inner_cast = ast.literal_eval(input_str) # type: List[str] if isinstance(inner_cast, list): return inner_cast else: raise ValueError
python
{ "resource": "" }
q34287
get_authors
train
def get_authors(filepath: str) -> List[str]: """Open file and check for author info.""" str_oneline = r'(^__author__ = )(\[.*?\])' # type" str comp_oneline = re.compile(str_oneline, re.MULTILINE) # type: Pattern[str] with open(filepath) as file_open: file_read = file_open.read() # type: str ...
python
{ "resource": "" }
q34288
scantree
train
def scantree(path: str) -> Generator: """Recursively yield DirEntry objects for given directory.""" for entry in os.scandir(path): if entry.is_dir(follow_symlinks=False): yield from scantree(entry.path) else: if entry.name.endswith('.py'): yield entry
python
{ "resource": "" }
q34289
write_contribs
train
def write_contribs(def_dict_list: Dict[str, List[str]]) -> None: """Write to file, in current dir, 'contributors.md'.""" file_str = '' # type: str note = '# Contributors\nCLTK Core authors, ordered alphabetically by first name\n\n' # type: str # pylint: disable=line-too-long file_str += note for ...
python
{ "resource": "" }
q34290
find_write_contribs
train
def find_write_contribs() -> None: """Look for files, find authors, sort, write file.""" map_file_auth = {} # type: Dict[str, List[str]] for filename in scantree('cltk'): filepath = filename.path # type: str authors_list = get_authors(filepath) # type: List[str] if authors_list: ...
python
{ "resource": "" }
q34291
Metre.syllabify
train
def syllabify(self, hierarchy): """ Syllables may play a role in verse classification. """ if len(self.long_lines) == 0: logger.error("No text was imported") self.syllabified_text = [] else: syllabifier = Syllabifier(language="old_norse", break...
python
{ "resource": "" }
q34292
Metre.to_phonetics
train
def to_phonetics(self): """ Transcribing words in verse helps find alliteration. """ if len(self.long_lines) == 0: logger.error("No text was imported") self.syllabified_text = [] else: transcriber = Transcriber(DIPHTHONGS_IPA, DIPHTHONGS_IPA_cl...
python
{ "resource": "" }
q34293
PoeticWord.parse_word_with
train
def parse_word_with(self, poetry_tools: PoetryTools): """ Compute the phonetic transcription of the word with IPA representation Compute the syllables of the word Compute the length of each syllable Compute if a syllable is stress of noe Compute the POS category the word ...
python
{ "resource": "" }
q34294
set_path
train
def set_path(dicts, keys, v): """ Helper function for modifying nested dictionaries :param dicts: dict: the given dictionary :param keys: list str: path to added value :param v: str: value to be added Example: >>> d = dict() >>> set_path(d, ['a', 'b', 'c'], 'd') >>> d ...
python
{ "resource": "" }
q34295
get_paths
train
def get_paths(src): """ Generates root-to-leaf paths, given a treebank in string format. Note that get_path is an iterator and does not return all the paths simultaneously. :param src: str: treebank Examples: >>> st = "((IP-MAT-SPE (' ') (INTJ Yes) (, ,) (' ') (IP-MAT-PRN (NP-SBJ (PRO he)) (VB...
python
{ "resource": "" }
q34296
Transliterate.transliterate
train
def transliterate(self, text, mode='Latin'): """ Transliterates Anglo-Saxon runes into latin and vice versa. Sources: http://www.arild-hauge.com/eanglor.htm https://en.wikipedia.org/wiki/Anglo-Saxon_runes :param text: str: The text to be transcribed :par...
python
{ "resource": "" }
q34297
SawyerNutAssembly.clear_objects
train
def clear_objects(self, obj): """ Clears objects with name @obj out of the task space. This is useful for supporting task modes with single types of objects, as in @self.single_object_mode without changing the model definition. """ for obj_name, obj_mjcf in self.mujoco_ob...
python
{ "resource": "" }
q34298
SawyerNutAssembly._check_contact
train
def _check_contact(self): """ Returns True if gripper is in contact with an object. """ collision = False for contact in self.sim.data.contact[: self.sim.data.ncon]: if ( self.sim.model.geom_id2name(contact.geom1) in self.finger_names o...
python
{ "resource": "" }
q34299
SawyerNutAssembly._check_success
train
def _check_success(self): """ Returns True if task has been completed. """ # remember objects that are on the correct pegs gripper_site_pos = self.sim.data.site_xpos[self.eef_site_id] for i in range(len(self.ob_inits)): obj_str = str(self.item_names[i]) + "0"...
python
{ "resource": "" }