_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q34100
Table.find_one
train
def find_one(self, *args, **kwargs): """Get a single result from the table. Works just like :py:meth:`find() <dataset.Table.find>` but returns one result, or ``None``. :: row = table.find_one(country='United States') """ if not self.exists: retur...
python
{ "resource": "" }
q34101
Table.count
train
def count(self, *_clauses, **kwargs): """Return the count of results for the given filter set.""" # NOTE: this does not have support for limit and offset since I can't # see how this is useful. Still, there might be compatibility issues # with people using these flags. Let's see how it g...
python
{ "resource": "" }
q34102
connect
train
def connect(url=None, schema=None, reflect_metadata=True, engine_kwargs=None, reflect_views=True, ensure_schema=True, row_type=row_type): """ Opens a new connection to a database. *url* can be any valid `SQLAlchemy engine URL`_. If *url* is not defined it will try to use *DATABASE_URL* from en...
python
{ "resource": "" }
q34103
Database.executable
train
def executable(self): """Connection against which statements will be executed.""" if not hasattr(self.local, 'conn'): self.local.conn = self.engine.connect() return self.local.conn
python
{ "resource": "" }
q34104
Database.in_transaction
train
def in_transaction(self): """Check if this database is in a transactional context.""" if not hasattr(self.local, 'tx'): return False return len(self.local.tx) > 0
python
{ "resource": "" }
q34105
Database.begin
train
def begin(self): """Enter a transaction explicitly. No data will be written until the transaction has been committed. """ if not hasattr(self.local, 'tx'): self.local.tx = [] self.local.tx.append(self.executable.begin())
python
{ "resource": "" }
q34106
Database.rollback
train
def rollback(self): """Roll back the current transaction. Discard all statements executed since the transaction was begun. """ if hasattr(self.local, 'tx') and self.local.tx: tx = self.local.tx.pop() tx.rollback() self._flush_tables()
python
{ "resource": "" }
q34107
Database.load_table
train
def load_table(self, table_name): """Load a table. This will fail if the tables does not already exist in the database. If the table exists, its columns will be reflected and are available on the :py:class:`Table <dataset.Table>` object. Returns a :py:class:`Table <dataset.Tabl...
python
{ "resource": "" }
q34108
Database.get_table
train
def get_table(self, table_name, primary_id=None, primary_type=None): """Load or create a table. This is now the same as ``create_table``. :: table = db.get_table('population') # you can also use the short-hand syntax: table = db['population'] """ ...
python
{ "resource": "" }
q34109
Database.query
train
def query(self, query, *args, **kwargs): """Run a statement on the database directly. Allows for the execution of arbitrary read/write queries. A query can either be a plain text string, or a `SQLAlchemy expression <http://docs.sqlalchemy.org/en/latest/core/tutorial.html#selecting>`_. ...
python
{ "resource": "" }
q34110
printcolour
train
def printcolour(text, sameline=False, colour=get_colour("ENDC")): """ Print color text using escape codes """ if sameline: sep = '' else: sep = '\n' sys.stdout.write(get_colour(colour) + text + bcolours["ENDC"] + sep)
python
{ "resource": "" }
q34111
abbreviate
train
def abbreviate(labels, rfill=' '): """ Abbreviate labels without introducing ambiguities. """ max_len = max(len(l) for l in labels) for i in range(1, max_len): abbrev = [l[:i].ljust(i, rfill) for l in labels] if len(abbrev) == len(set(abbrev)): break return abbrev
python
{ "resource": "" }
q34112
box_text
train
def box_text(text, width, offset=0): """ Return text inside an ascii textbox """ box = " " * offset + "-" * (width+2) + "\n" box += " " * offset + "|" + text.center(width) + "|" + "\n" box += " " * offset + "-" * (width+2) return box
python
{ "resource": "" }
q34113
calc_bins
train
def calc_bins(n, min_val, max_val, h=None, binwidth=None): """ Calculate number of bins for the histogram """ if not h: h = max(10, math.log(n + 1, 2)) if binwidth == 0: binwidth = 0.1 if binwidth is None: binwidth = (max_val - min_val) / h for b in drange(min_val, ma...
python
{ "resource": "" }
q34114
read_numbers
train
def read_numbers(numbers): """ Read the input data in the most optimal way """ if isiterable(numbers): for number in numbers: yield float(str(number).strip()) else: with open(numbers) as fh: for number in fh: yield float(number.strip())
python
{ "resource": "" }
q34115
run_demo
train
def run_demo(): """ Run a demonstration """ module_dir = dirname(dirname(os.path.realpath(__file__))) demo_file = os.path.join(module_dir, 'examples/data/exp.txt') if not os.path.isfile(demo_file): sys.stderr.write("demo input file not found!\n") sys.stderr.write("run the downlo...
python
{ "resource": "" }
q34116
plot_scatter
train
def plot_scatter(f, xs, ys, size, pch, colour, title): """ Form a complex number. Arguments: f -- comma delimited file w/ x,y coordinates xs -- if f not specified this is a file w/ x coordinates ys -- if f not specified this is a filew / y coordinates size -- size of the plo...
python
{ "resource": "" }
q34117
Word.syllabify
train
def syllabify(self): """ Syllabifier module for Middle High German The algorithm works by applying the MOP(Maximal Onset Principle) on open syllables. For closed syllables, the legal partitions are checked and applied. The word is always returned in lowercase. Examples:...
python
{ "resource": "" }
q34118
Word.ASCII_encoding
train
def ASCII_encoding(self): """Returns the ASCII encoding of a string""" w = unicodedata.normalize('NFKD', self.word).encode('ASCII', 'ignore') # Encode into ASCII, returns a bytestring w = w.decode('utf-8') # Convert back to string ...
python
{ "resource": "" }
q34119
ATFConverter._convert_consonant
train
def _convert_consonant(sign): """ Uses dictionary to replace ATF convention for unicode characters. input = ['as,', 'S,ATU', 'tet,', 'T,et', 'sza', 'ASZ'] output = ['aṣ', 'ṢATU', 'teṭ', 'Ṭet', 'ša', 'AŠ'] :param sign: string :return: string """ for key i...
python
{ "resource": "" }
q34120
ATFConverter._convert_number_to_subscript
train
def _convert_number_to_subscript(num): """ Converts number into subscript input = ["a", "a1", "a2", "a3", "be2", "be3", "bad2", "bad3"] output = ["a", "a₁", "a₂", "a₃", "be₂", "be₃", "bad₂", "bad₃"] :param num: number called after sign :return: number in subscript ...
python
{ "resource": "" }
q34121
ATFConverter._convert_num
train
def _convert_num(self, sign): """ Converts number registered in get_number_from_sign. input = ["a2", "☉", "be3"] output = ["a₂", "☉", "be₃"] :param sign: string :return sign: string """ # Check if there's a number at the end new_sign, num = self....
python
{ "resource": "" }
q34122
ATFConverter.process
train
def process(self, text_string): """ Expects a list of tokens, will return the list converted from ATF format to print-format. input = ["a", "a2", "a3", "geme2", "bad3", "buru14"] output = ["a", "á", "à", "géme", "bàd", "buru₁₄"] :param text_string: string :retur...
python
{ "resource": "" }
q34123
Levenshtein.Levenshtein_Distance
train
def Levenshtein_Distance(w1, w2): """ Computes Levenshtein Distance between two words Args: :param w1: str :param w2: str :return: int Examples: >>> Levenshtein.Levenshtein_Distance('noctis', 'noctem') 2 >>> Leve...
python
{ "resource": "" }
q34124
Levenshtein.Damerau_Levenshtein_Distance
train
def Damerau_Levenshtein_Distance(w1, w2): """ Computes Damerau-Levenshtein Distance between two words Args: :param w1: str :param w2: str :return int: Examples: For the most part, Damerau-Levenshtein behaves identically to Lev...
python
{ "resource": "" }
q34125
Frequency.counter_from_str
train
def counter_from_str(self, string): """Build word frequency list from incoming string.""" string_list = [chars for chars in string if chars not in self.punctuation] string_joined = ''.join(string_list) tokens = self.punkt.word_tokenize(string_joined) return Counter(tokens)
python
{ "resource": "" }
q34126
Frequency._assemble_corpus_string
train
def _assemble_corpus_string(self, corpus): """Takes a list of filepaths, returns a string containing contents of all files.""" if corpus == 'phi5': filepaths = assemble_phi5_author_filepaths() file_cleaner = phi5_plaintext_cleanup elif corpus == 'tlg': ...
python
{ "resource": "" }
q34127
remove_punctuation_dict
train
def remove_punctuation_dict() -> Dict[int, None]: """ Provide a dictionary for removing punctuation, swallowing spaces. :return dict with punctuation from the unicode table >>> print("I'm ok! Oh #%&*()[]{}!? Fine!".translate( ... remove_punctuation_dict()).lstrip()) Im ok Oh Fine """ ...
python
{ "resource": "" }
q34128
punctuation_for_spaces_dict
train
def punctuation_for_spaces_dict() -> Dict[int, str]: """ Provide a dictionary for removing punctuation, keeping spaces. Essential for scansion to keep stress patterns in alignment with original vowel positions in the verse. :return dict with punctuation from the unicode table >>> print("I'm ok! Oh...
python
{ "resource": "" }
q34129
differences
train
def differences(scansion: str, candidate: str) -> List[int]: """ Given two strings, return a list of index positions where the contents differ. :param scansion: :param candidate: :return: >>> differences("abc", "abz") [2] """ before = scansion.replace(" ", "") after = candidate...
python
{ "resource": "" }
q34130
space_list
train
def space_list(line: str) -> List[int]: """ Given a string, return a list of index positions where a blank space occurs. :param line: :return: >>> space_list(" abc ") [0, 1, 2, 3, 7] """ spaces = [] for idx, car in enumerate(list(line)): if car == " ": spaces...
python
{ "resource": "" }
q34131
to_syllables_with_trailing_spaces
train
def to_syllables_with_trailing_spaces(line: str, syllables: List[str]) -> List[str]: """ Given a line of syllables and spaces, and a list of syllables, produce a list of the syllables with trailing spaces attached as approriate. :param line: :param syllables: :return: >>> to_syllables_with...
python
{ "resource": "" }
q34132
join_syllables_spaces
train
def join_syllables_spaces(syllables: List[str], spaces: List[int]) -> str: """ Given a list of syllables, and a list of integers indicating the position of spaces, return a string that has a space inserted at the designated points. :param syllables: :param spaces: :return: >>> join_syllabl...
python
{ "resource": "" }
q34133
stress_positions
train
def stress_positions(stress: str, scansion: str) -> List[int]: """ Given a stress value and a scansion line, return the index positions of the stresses. :param stress: :param scansion: :return: >>> stress_positions("-", " - U U - UU - U U") [0, 3, 6] """ line = scansion.re...
python
{ "resource": "" }
q34134
merge_elisions
train
def merge_elisions(elided: List[str]) -> str: """ Given a list of strings with different space swapping elisions applied, merge the elisions, taking the most without compounding the omissions. :param elided: :return: >>> merge_elisions([ ... "ignavae agua multum hiatus", "ignav agua mult...
python
{ "resource": "" }
q34135
move_consonant_right
train
def move_consonant_right(letters: List[str], positions: List[int]) -> List[str]: """ Given a list of letters, and a list of consonant positions, move the consonant positions to the right, merging strings as necessary. :param letters: :param positions: :return: >>> move_consonant_right(list...
python
{ "resource": "" }
q34136
move_consonant_left
train
def move_consonant_left(letters: List[str], positions: List[int]) -> List[str]: """ Given a list of letters, and a list of consonant positions, move the consonant positions to the left, merging strings as necessary. :param letters: :param positions: :return: >>> move_consonant_left(['a', '...
python
{ "resource": "" }
q34137
merge_next
train
def merge_next(letters: List[str], positions: List[int]) -> List[str]: """ Given a list of letter positions, merge each letter with its next neighbor. :param letters: :param positions: :return: >>> merge_next(['a', 'b', 'o', 'v', 'o' ], [0, 2]) ['ab', '', 'ov', '', 'o'] >>> # Note: bec...
python
{ "resource": "" }
q34138
remove_blanks
train
def remove_blanks(letters: List[str]): """ Given a list of letters, remove any empty strings. :param letters: :return: >>> remove_blanks(['a', '', 'b', '', 'c']) ['a', 'b', 'c'] """ cleaned = [] for letter in letters: if letter != "": cleaned.append(letter) ...
python
{ "resource": "" }
q34139
split_on
train
def split_on(word: str, section: str) -> Tuple[str, str]: """ Given a string, split on a section, and return the two sections as a tuple. :param word: :param section: :return: >>> split_on('hamrye', 'ham') ('ham', 'rye') """ return word[:word.index(section)] + section, word[word.in...
python
{ "resource": "" }
q34140
remove_blank_spaces
train
def remove_blank_spaces(syllables: List[str]) -> List[str]: """ Given a list of letters, remove any blank spaces or empty strings. :param syllables: :return: >>> remove_blank_spaces(['', 'a', ' ', 'b', ' ', 'c', '']) ['a', 'b', 'c'] """ cleaned = [] for syl in syllables: if...
python
{ "resource": "" }
q34141
overwrite
train
def overwrite(char_list: List[str], regexp: str, quality: str, offset: int = 0) -> List[str]: """ Given a list of characters and spaces, a matching regular expression, and a quality or character, replace the matching character with a space, overwriting with an offset and a multiplier if provided. :...
python
{ "resource": "" }
q34142
get_unstresses
train
def get_unstresses(stresses: List[int], count: int) -> List[int]: """ Given a list of stressed positions, and count of possible positions, return a list of the unstressed positions. :param stresses: a list of stressed positions :param count: the number of possible positions :return: a list of u...
python
{ "resource": "" }
q34143
decline_strong_masculine_noun
train
def decline_strong_masculine_noun(ns: str, gs: str, np: str): """ Gives the full declension of strong masculine nouns. >>> decline_strong_masculine_noun("armr", "arms", "armar") armr arm armi arms armar arma örmum arma # >>> decline_strong_masculine_noun("ketill", "keti...
python
{ "resource": "" }
q34144
decline_strong_feminine_noun
train
def decline_strong_feminine_noun(ns: str, gs: str, np: str): """ Gives the full declension of strong feminine nouns. o macron-stem Most of strong feminine nouns follows the declension of rún and för. >>> decline_strong_feminine_noun("rún", "rúnar", "rúnar") rún rún rún rúnar rún...
python
{ "resource": "" }
q34145
decline_strong_neuter_noun
train
def decline_strong_neuter_noun(ns: str, gs: str, np: str): """ Gives the full declension of strong neuter nouns. a-stem Most of strong neuter nouns follow the declensions of skip, land and herað. >>> decline_strong_neuter_noun("skip", "skips", "skip") skip skip skipi skips skip...
python
{ "resource": "" }
q34146
decline_weak_masculine_noun
train
def decline_weak_masculine_noun(ns: str, gs: str, np: str): """ Gives the full declension of weak masculine nouns. >>> decline_weak_masculine_noun("goði", "goða", "goðar") goði goða goða goða goðar goða goðum goða >>> decline_weak_masculine_noun("hluti", "hluta", "hluta...
python
{ "resource": "" }
q34147
decline_weak_feminine_noun
train
def decline_weak_feminine_noun(ns: str, gs: str, np: str): """ Gives the full declension of weak feminine nouns. >>> decline_weak_feminine_noun("saga", "sögu", "sögur") saga sögu sögu sögu sögur sögur sögum sagna >>> decline_weak_feminine_noun("kona", "konu", "konur") ...
python
{ "resource": "" }
q34148
decline_weak_neuter_noun
train
def decline_weak_neuter_noun(ns: str, gs: str, np: str): """ Gives the full declension of weak neuter nouns. >>> decline_weak_neuter_noun("auga", "auga", "augu") auga auga auga auga augu augu augum augna >>> decline_weak_neuter_noun("hjarta", "hjarta", "hjörtu") hja...
python
{ "resource": "" }
q34149
select_id_by_name
train
def select_id_by_name(query): """Do a case-insensitive regex match on author name, returns TLG id.""" id_author = get_id_author() comp = regex.compile(r'{}'.format(query.casefold()), flags=regex.VERSION1) matches = [] for _id, author in id_author.items(): match = comp.findall(author.casefold...
python
{ "resource": "" }
q34150
get_date_of_author
train
def get_date_of_author(_id): """Pass author id and return the name of its associated date.""" _dict = get_date_author() for date, ids in _dict.items(): if _id in ids: return date return None
python
{ "resource": "" }
q34151
_get_epoch
train
def _get_epoch(_str): """Take incoming string, return its epoch.""" _return = None if _str.startswith('A.D. '): _return = 'ad' elif _str.startswith('a. A.D. '): _return = None #? elif _str.startswith('p. A.D. '): _return = 'ad' elif regex.match(r'^[0-9]+ B\.C\. *', _str):...
python
{ "resource": "" }
q34152
NaiveDecliner.decline_noun
train
def decline_noun(self, noun, gender, mimation=True): """Return a list of all possible declined forms given any form of a noun and its gender.""" stem = self.stemmer.get_stem(noun, gender) declension = [] for case in self.endings[gender]['singular']: if gender == 'm':...
python
{ "resource": "" }
q34153
stem
train
def stem(text): """make string lower-case""" text = text.lower() """Stem each word of the French text.""" stemmed_text = '' word_tokenizer = WordTokenizer('french') tokenized_text = word_tokenizer.tokenize(text) for word in tokenized_text: """remove the simple endings from the targ...
python
{ "resource": "" }
q34154
VerseScanner.transform_i_to_j_optional
train
def transform_i_to_j_optional(self, line: str) -> str: """ Sometimes for the demands of meter a more permissive i to j transformation is warranted. :param line: :return: >>> print(VerseScanner().transform_i_to_j_optional("Italiam")) Italjam >>> print(VerseScanne...
python
{ "resource": "" }
q34155
VerseScanner.accent_by_position
train
def accent_by_position(self, verse_line: str) -> str: """ Accent vowels according to the rules of scansion. :param verse_line: a line of unaccented verse :return: the same line with vowels accented by position >>> print(VerseScanner().accent_by_position( ... "Arma virum...
python
{ "resource": "" }
q34156
VerseScanner.calc_offset
train
def calc_offset(self, syllables_spaces: List[str]) -> Dict[int, int]: """ Calculate a dictionary of accent positions from a list of syllables with spaces. :param syllables_spaces: :return: """ line = string_utils.flatten(syllables_spaces) mydict = {} # type: Dict...
python
{ "resource": "" }
q34157
VerseScanner.produce_scansion
train
def produce_scansion(self, stresses: list, syllables_wspaces: List[str], offset_map: Dict[int, int]) -> str: """ Create a scansion string that has stressed and unstressed syllable positions in locations that correspond with the original texts syllable vowels. :p...
python
{ "resource": "" }
q34158
VerseScanner.flag_dipthongs
train
def flag_dipthongs(self, syllables: List[str]) -> List[int]: """ Return a list of syllables that contain a dipthong :param syllables: :return: """ long_positions = [] for idx, syl in enumerate(syllables): for dipthong in self.constants.DIPTHONGS: ...
python
{ "resource": "" }
q34159
VerseScanner.elide
train
def elide(self, line: str, regexp: str, quantity: int = 1, offset: int = 0) -> str: """ Erase a section of a line, matching on a regex, pushing in a quantity of blank spaces, and jumping forward with an offset if necessary. If the elided vowel was strong, the vowel merged with takes on t...
python
{ "resource": "" }
q34160
VerseScanner.assign_candidate
train
def assign_candidate(self, verse: Verse, candidate: str) -> Verse: """ Helper method; make sure that the verse object is properly packaged. :param verse: :param candidate: :return: """ verse.scansion = candidate verse.valid = True verse.accented =...
python
{ "resource": "" }
q34161
CollatinusDecliner.__getRoots
train
def __getRoots(self, lemma, model=None): """ Retrieve the known roots of a lemma :param lemma: Canonical form of the word (lemma) :type lemma: str :param model_roots: Model data from the loaded self.__data__. Can be passed by decline() :type model_roots: dict :return: Di...
python
{ "resource": "" }
q34162
CollatinusDecliner.decline
train
def decline(self, lemma, flatten=False, collatinus_dict=False): """ Decline a lemma .. warning:: POS are incomplete as we do not detect the type outside of verbs, participle and adjective. :raise UnknownLemma: When the lemma is unknown to our data :param lemma: Lemma (Canonical form) ...
python
{ "resource": "" }
q34163
_sentence_context
train
def _sentence_context(match, language='latin', case_insensitive=True): """Take one incoming regex match object and return the sentence in which the match occurs. :rtype : str :param match: regex.match :param language: str """ language_punct = {'greek': r'\.|;', 'lati...
python
{ "resource": "" }
q34164
match_regex
train
def match_regex(input_str, pattern, language, context, case_insensitive=True): """Take input string and a regex pattern, then yield generator of matches in desired format. TODO: Rename this `match_pattern` and incorporate the keyword expansion code currently in search_corpus. :param input_str:...
python
{ "resource": "" }
q34165
make_worlist_trie
train
def make_worlist_trie(wordlist): """ Creates a nested dictionary representing the trie created by the given word list. :param wordlist: str list: :return: nested dictionary >>> make_worlist_trie(['einander', 'einen', 'neben']) {'e': {'i': {'n': {'a': {'n': {'d': {'e': {'r': {'__end__': '__...
python
{ "resource": "" }
q34166
MetricalValidator.is_valid_hendecasyllables
train
def is_valid_hendecasyllables(self, scanned_line: str) -> bool: """Determine if a scansion pattern is one of the valid Hendecasyllables metrical patterns :param scanned_line: a line containing a sequence of stressed and unstressed syllables :return bool >>> print(MetricalValidator().is...
python
{ "resource": "" }
q34167
MetricalValidator.is_valid_pentameter
train
def is_valid_pentameter(self, scanned_line: str) -> bool: """Determine if a scansion pattern is one of the valid Pentameter metrical patterns :param scanned_line: a line containing a sequence of stressed and unstressed syllables :return bool: whether or not the scansion is a valid pen...
python
{ "resource": "" }
q34168
MetricalValidator.hexameter_feet
train
def hexameter_feet(self, scansion: str) -> List[str]: """ Produces a list of hexameter feet, stressed and unstressed syllables with spaces intact. If the scansion line is not entirely correct, it will attempt to corral one or more improper patterns into one or more feet. :param:...
python
{ "resource": "" }
q34169
MetricalValidator.closest_hexameter_patterns
train
def closest_hexameter_patterns(self, scansion: str) -> List[str]: """ Find the closest group of matching valid hexameter patterns. :return: list of the closest valid hexameter patterns; only candidates with a matching length/number of syllables are considered. >>> print(Metrica...
python
{ "resource": "" }
q34170
MetricalValidator.closest_pentameter_patterns
train
def closest_pentameter_patterns(self, scansion: str) -> List[str]: """ Find the closest group of matching valid pentameter patterns. :return: list of the closest valid pentameter patterns; only candidates with a matching length/number of syllables are considered. >>> print(Metr...
python
{ "resource": "" }
q34171
MetricalValidator.closest_hendecasyllable_patterns
train
def closest_hendecasyllable_patterns(self, scansion: str) -> List[str]: """ Find the closest group of matching valid hendecasyllable patterns. :return: list of the closest valid hendecasyllable patterns; only candidates with a matching length/number of syllables are considered. ...
python
{ "resource": "" }
q34172
MetricalValidator._closest_patterns
train
def _closest_patterns(self, patterns: List[str], scansion: str) -> List[str]: """ Find the closest group of matching valid patterns. :patterns: a list of patterns :scansion: the scansion pattern thus far :return: list of the closest valid patterns; only candidates with a matchin...
python
{ "resource": "" }
q34173
MetricalValidator._build_pentameter_templates
train
def _build_pentameter_templates(self) -> List[str]: """Create pentameter templates.""" return [ # '-UU|-UU|-|-UU|-UU|X' self.constants.DACTYL + self.constants.DACTYL + self.constants.STRESSED + self.constants.DACTYL + self.constants.DACTYL + self.constants.OPTIONAL_E...
python
{ "resource": "" }
q34174
LemmaReplacer._load_replacement_patterns
train
def _load_replacement_patterns(self): """Check for availability of lemmatizer for a language.""" if self.language == 'latin': warnings.warn( "LemmaReplacer is deprecated and will soon be removed from CLTK. Please use the BackoffLatinLemmatizer at cltk.lemmatize.latin....
python
{ "resource": "" }
q34175
Needleman_Wunsch
train
def Needleman_Wunsch(w1, w2, d=-1, alphabet = "abcdefghijklmnopqrstuvwxyz", S = Default_Matrix(26, 1, -1) ): """ Computes allignment using Needleman-Wunsch algorithm. The alphabet parameter is used for specifying the alphabetical order of the similarity matrix. Similarity matrix is initialized to an un...
python
{ "resource": "" }
q34176
CDLICorpus.toc
train
def toc(self): """ Returns a rich list of texts in the catalog. """ output = [] for key in sorted(self.catalog.keys()): edition = self.catalog[key]['edition'] length = len(self.catalog[key]['transliteration']) output.append( "Pn...
python
{ "resource": "" }
q34177
englishToPun_number
train
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[in...
python
{ "resource": "" }
q34178
is_indiclang_char
train
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
{ "resource": "" }
q34179
is_velar
train
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
{ "resource": "" }
q34180
is_palatal
train
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
{ "resource": "" }
q34181
is_retroflex
train
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
{ "resource": "" }
q34182
is_dental
train
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
{ "resource": "" }
q34183
is_labial
train
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
{ "resource": "" }
q34184
Verse.to_phonetics
train
def to_phonetics(self): """Transcribe phonetics.""" tr = Transcriber() self.transcribed_phonetics = [tr.transcribe(line) for line in self.text]
python
{ "resource": "" }
q34185
PositionedPhoneme
train
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 whe...
python
{ "resource": "" }
q34186
PhonemeDisjunction.matches
train
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([ph...
python
{ "resource": "" }
q34187
Orthophonology.transcribe
train
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 = [sel...
python
{ "resource": "" }
q34188
Orthophonology.transcribe_to_modern
train
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_phon...
python
{ "resource": "" }
q34189
Orthophonology.voice
train
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
{ "resource": "" }
q34190
Orthophonology.aspirate
train
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_conson...
python
{ "resource": "" }
q34191
BaseSentenceTokenizerTrainer.train_sentence_tokenizer
train
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 + sel...
python
{ "resource": "" }
q34192
FilteredPlaintextCorpusReader.docs
train
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 ge...
python
{ "resource": "" }
q34193
FilteredPlaintextCorpusReader.sizes
train
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 generato...
python
{ "resource": "" }
q34194
TesseraeCorpusReader.docs
train
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(p...
python
{ "resource": "" }
q34195
TesseraeCorpusReader.lines
train
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'): ...
python
{ "resource": "" }
q34196
TesseraeCorpusReader.sents
train
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
{ "resource": "" }
q34197
TesseraeCorpusReader.words
train
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
{ "resource": "" }
q34198
TesseraeCorpusReader.pos_tokenize
train
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
{ "resource": "" }
q34199
TesseraeCorpusReader.describe
train
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...
python
{ "resource": "" }