code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
css_list = [DEFAULT_MARK_CSS]
for aes in self.aesthetics:
css_list.extend(get_mark_css(aes, self.values[aes]))
#print('\n'.join(css_list))
return '\n'.join(css_list) | def css(self) | Returns
-------
str
The CSS. | 5.434164 | 6.161584 | 0.881943 |
html = mark_text(text, self.aesthetics, self.rules)
html = html.replace('\n', '<br/>')
if add_header:
html = '\n'.join([HEADER, self.css, MIDDLE, html, FOOTER])
#print('\n'.join((HEADER, self.css, MIDDLE, html, FOOTER)))
return html | def render(self, text, add_header=False) | Render the HTML.
Parameters
----------
add_header: boolean (default: False)
If True, add HTML5 header and footer.
Returns
-------
str
The rendered HTML. | 4.448515 | 4.587989 | 0.9696 |
trainer = pycrfsuite.Trainer(algorithm=self.algorithm,
params={'c2': self.c2},
verbose=self.verbose)
for doc in nerdocs:
for snt in doc.sentences:
xseq = [t.feature_list() for t in snt]
... | def train(self, nerdocs, mode_filename) | Train a CRF model using given documents.
Parameters
----------
nerdocs: list of estnltk.estner.ner.Document.
The documents for model training.
mode_filename: str
The fielname where to save the model. | 3.105516 | 3.219633 | 0.964556 |
labels = []
for snt in nerdoc.sentences:
xseq = [t.feature_list() for t in snt]
yseq = self.tagger.tag(xseq)
labels.append(yseq)
return labels | def tag(self, nerdoc) | Tag the given document.
Parameters
----------
nerdoc: estnltk.estner.Document
The document to be tagged.
Returns
-------
labels: list of lists of str
Predicted token Labels for each sentence in the document | 4.433222 | 3.92224 | 1.130278 |
openbr = 0
cur = 0
for char in text:
cur +=1
if char == openDelim:
openbr += 1
if char == closeDelim:
openbr -= 1
if openbr == 0:
break
return text[:cur], cur | def balancedSlicer(text, openDelim='[', closeDelim=']') | Assuming that text contains a properly balanced expression using
:param openDelim: as opening delimiters and
:param closeDelim: as closing delimiters.
:return: text between the delimiters | 2.755408 | 3.179015 | 0.866749 |
for root, dirs, filenames in os.walk(inp):
for f in filenames:
log = codecs.open(os.path.join(root, f), 'r')
j_obj = json.load(log)
j_obj = json_format(j_obj)
#not needed, cause the json_format takes care of the right structuring
#text = Tex... | def json_2_text(inp, out, verbose = False) | Convert a Wikipedia article to Text object.
Concatenates the sections in wikipedia file and rearranges other information so it
can be interpreted as a Text object.
Links and other elements with start and end positions are annotated
as layers.
Parameters
----------
inp: directory of parsed ... | 5.247864 | 4.981635 | 1.053442 |
match = Match(a.start, b.end, text[a.start:b.end], name)
for k, v in a.matches.items():
match.matches[k] = v
for k, v in b.matches.items():
match.matches[k] = v
if a.name is not None:
aa = copy(a)
del aa[MATCHES]
match.matches[a.name] = aa
if b.name is no... | def concatenate_matches(a, b, text, name) | Concatenate matches a and b.
All submatches will be copied to result. | 2.143438 | 2.085861 | 1.027604 |
res = copy(self)
if MATCHES in res:
del res[MATCHES]
if NAME in res:
del res[NAME]
res = {self.name: res}
for k, v in self.matches.items():
res[k] = v
if NAME in res[k]:
del res[k][NAME]
return res | def dict(self) | Dictionary representing this match and all child symbol matches. | 3.297526 | 3.023471 | 1.090642 |
return re.compile('|'.join([re.escape(c) for c in markers])) | def regex_from_markers(markers) | Given a string of characters, construct a regex that matches them.
Parameters
----------
markers: str
The list of string containing the markers
Returns
-------
regex
The regular expression matching the given markers. | 4.358694 | 8.682264 | 0.502023 |
if six.PY2:
if isinstance(word, unicode):
return word.encode('utf-8')
else:
return word.decode('utf-8').encode('utf-8') # make sure it is real utf8, otherwise complain
else: # ==> Py3
if isinstance(word, bytes):
return word.decode('utf-8') # bytes... | def convert(word) | This method converts given `word` to UTF-8 encoding and `bytes` type for the
SWIG wrapper. | 4.342689 | 4.242505 | 1.023614 |
word, analysis = morphresult
return {
'text': deconvert(word),
'analysis': [postprocess_analysis(a, trim_phonetic, trim_compound) for a in analysis]
} | def postprocess_result(morphresult, trim_phonetic, trim_compound) | Postprocess vabamorf wrapper output. | 4.904606 | 4.727903 | 1.037375 |
global phonetic_markers
global phonetic_regex
if root in phonetic_markers:
return root
else:
return phonetic_regex.sub('', root) | def trim_phonetics(root) | Function that trims phonetic markup from the root.
Parameters
----------
root: str
The string to remove the phonetic markup.
Returns
-------
str
The string with phonetic markup removed. | 3.746546 | 4.194435 | 0.893218 |
global compound_regex
if not phonetic:
root = trim_phonetics(root)
if not compound:
root = trim_compounds(root)
return root | def get_root(root, phonetic, compound) | Get the root form without markers.
Parameters
----------
root: str
The word root form.
phonetic: boolean
If True, add phonetic information to the root forms.
compound: boolean
if True, add compound word markers to root forms. | 5.045793 | 5.760799 | 0.875884 |
global all_markers
if root in all_markers or root in ['-', '_']: # special case
return [[root]]
groups = []
for group in root.split('-'):
toks = [trim_phonetics(trim_compounds(tok)) for tok in group.split('_')]
groups.append(toks)
return groups | def get_group_tokens(root) | Function to extract tokens in hyphenated groups (saunameheks-tallimeheks).
Parameters
----------
root: str
The root form.
Returns
-------
list of (list of str)
List of grouped root tokens. | 7.419909 | 7.813946 | 0.949573 |
return Vabamorf.instance().fix_spelling(words, join, joinstring) | def fix_spelling(words, join=True, joinstring=' ') | Simple function for quickly correcting misspelled words.
Parameters
----------
words: list of str or str
Either a list of pretokenized words or a string. In case of a string, it will be splitted using
default behaviour of string.split() function.
join: boolean (default: True)
Sh... | 22.180882 | 38.872929 | 0.5706 |
return Vabamorf.instance().synthesize(lemma, form, partofspeech, hint, guess, phonetic) | def synthesize(lemma, form, partofspeech='', hint='', guess=True, phonetic=False) | Synthesize a single word based on given morphological attributes.
Note that spellchecker does not respect pre-tokenized words and concatenates
token sequences such as "New York".
Parameters
----------
lemma: str
The lemma of the word(s) to be synthesized.
form: str
The form of ... | 7.3371 | 14.772761 | 0.496664 |
if not hasattr(Vabamorf, 'pid') or Vabamorf.pid != os.getpid():
Vabamorf.pid = os.getpid()
Vabamorf.morf = Vabamorf()
return Vabamorf.morf | def instance() | Return an PyVabamorf instance.
It returns the previously initialized instance or creates a new
one if nothing exists. Also creates new instance in case the
process has been forked. | 4.169577 | 2.477213 | 1.683172 |
# if input is a string, then tokenize it
if isinstance(words, six.string_types):
words = words.split()
# convert words to native strings
words = [convert(w) for w in words]
morfresults = self._morf.analyze(
vm.StringVector(words),
kw... | def analyze(self, words, **kwargs) | Perform morphological analysis and disambiguation of given text.
Parameters
----------
words: list of str or str
Either a list of pretokenized words or a string. In case of a string, it will be splitted using
default behaviour of string.split() function.
disambig... | 5.156601 | 4.151871 | 1.241994 |
words = vm.SentenceAnalysis([as_wordanalysis(w) for w in words])
disambiguated = self._morf.disambiguate(words)
return [postprocess_result(mr, False, True) for mr in disambiguated] | def disambiguate(self, words) | Disambiguate previously analyzed words.
Parameters
----------
words: list of dict
A sentence of words.
Returns
-------
list of dict
Sentence of disambiguated words. | 9.30879 | 12.761566 | 0.729439 |
if isinstance(words, six.string_types):
words = words.split()
# convert words to native strings
words = [convert(w) for w in words]
spellresults = self._morf.spellcheck(words, suggestions)
results = []
for spellresult in spellresults:
su... | def spellcheck(self, words, suggestions=True) | Spellcheck given sentence.
Note that spellchecker does not respect pre-tokenized words and concatenates
token sequences such as "New York".
Parameters
----------
words: list of str or str
Either a list of pretokenized words or a string. In case of a string, it will ... | 2.979122 | 3.390992 | 0.87854 |
fixed_words = []
for word in self.spellcheck(words, suggestions=True):
if word['spelling']:
fixed_words.append(word['text'])
else:
suggestions = word['suggestions']
if len(suggestions) > 0:
fixed_words.... | def fix_spelling(self, words, join=True, joinstring=' ') | Simple function for quickly correcting misspelled words.
Parameters
----------
words: list of str or str
Either a list of pretokenized words or a string. In case of a string, it will be splitted using
default behaviour of string.split() function.
join: boolean (d... | 2.289819 | 2.504337 | 0.914341 |
words = self._morf.synthesize(
convert(lemma.strip()),
convert(form.strip()),
convert(partofspeech.strip()),
convert(hint.strip()),
guess,
phonetic
)
return [deconvert(w) for w in words] | def synthesize(self, lemma, form, partofspeech='', hint='', guess=True, phonetic=False) | Synthesize a single word based on given morphological attributes.
Note that spellchecker does not respect pre-tokenized words and concatenates
token sequences such as "New York".
Parameters
----------
lemma: str
The lemma of the word(s) to be synthesized.
fo... | 3.629281 | 4.549115 | 0.797799 |
# depending on how the morphological analysis was added, there may be
# phonetic markup. Remove it, if it exists.
for word in sentence:
for analysis in word[ANALYSIS]:
analysis[ROOT] = analysis[ROOT].replace('~', '')
analysis[ROOT] = re.sub('[... | def prepare_sentence(self, sentence) | Prepare the sentence for segment detection. | 12.255211 | 12.225444 | 1.002435 |
max_index = 0
max_depth = 1
stack_of_indexes = [ max_index ]
for token in sentence:
if CLAUSE_ANNOT not in token:
token[CLAUSE_IDX] = stack_of_indexes[-1]
else:
# Alustavad märgendused
for annotation in toke... | def annotate_indices(self, sentence) | Add clause indexes to already annotated sentence. | 5.383855 | 5.243688 | 1.026731 |
annotations = []
for token in sentence:
data = {CLAUSE_IDX: token[CLAUSE_IDX]}
if CLAUSE_ANNOT in token:
if 'KINDEL_PIIR' in token[CLAUSE_ANNOT]:
data[CLAUSE_ANNOTATION] = CLAUSE_BOUNDARY
elif 'KIILU_ALGUS' in token[CLA... | def rename_annotations(self, sentence) | Function that renames and restructures clause information. | 3.78301 | 3.660176 | 1.033559 |
''' Re-formats time duration in seconds (*sec*) into more easily readable
form, where (days,) hours, minutes, and seconds are explicitly shown.
Returns the new duration as a formatted string.
'''
import time
if sec < 864000:
# Idea from: http://stackoverflow.com/a/1384565
... | def format_time( sec ) | Re-formats time duration in seconds (*sec*) into more easily readable
form, where (days,) hours, minutes, and seconds are explicitly shown.
Returns the new duration as a formatted string. | 5.157755 | 2.529081 | 2.039379 |
''' Tokenizes the *text* (from *file_name*) into sentences, and if the number of
sentences exceeds *max_sentences*, splits the text into smaller texts.
Returns a list containing the original text (if no splitting was required),
or a list containing results of the splitting (smaller texts);... | def split_Text( text, file_name, verbose = True ) | Tokenizes the *text* (from *file_name*) into sentences, and if the number of
sentences exceeds *max_sentences*, splits the text into smaller texts.
Returns a list containing the original text (if no splitting was required),
or a list containing results of the splitting (smaller texts); | 4.304159 | 3.581969 | 1.201618 |
''' Based on *old_file_name*, *suffix* and *out_dir*, constructs a new file name and
writes *text* (in the ascii normalised JSON format) into the new file.
'''
name = os.path.basename( old_file_name )
if '.' in name:
new_name = re.sub('\.([^.]+)$', suffix+'.\\1', name)
else:
... | def write_Text_into_file( text, old_file_name, out_dir, suffix='__split', verbose=True ) | Based on *old_file_name*, *suffix* and *out_dir*, constructs a new file name and
writes *text* (in the ascii normalised JSON format) into the new file. | 4.944479 | 3.425338 | 1.443501 |
documents = []
for fnm in get_filenames(root, prefix, suffix):
path = os.path.join(root, fnm)
docs = parse_tei_corpus(path, target, encoding)
for doc in docs:
doc[FILE] = fnm
documents.extend(docs)
return documents | def parse_tei_corpora(root, prefix='', suffix='.xml', target=['artikkel'], encoding=None) | Parse documents from TEI style XML files.
Gives each document FILE attribute that denotes the original filename.
Parameters
----------
root: str
The directory path containing the TEI corpora XMl files.
prefix: str
The prefix of filenames to include (default: '')
suffix:... | 2.87784 | 3.08326 | 0.933376 |
with open(path, 'rb') as f:
html_doc = f.read()
if encoding:
html_doc = html_doc.decode( encoding )
soup = BeautifulSoup(html_doc, 'html5lib')
title = soup.find_all('title')[0].string
documents = []
for div1 in soup.find_all('div1'):
documents.extend(parse_div(d... | def parse_tei_corpus(path, target=['artikkel'], encoding=None) | Parse documents from a TEI style XML file.
Parameters
----------
path: str
The path of the XML file.
target: list of str
List of <div> types, that are considered documents in the XML files (default: ["artikkel"]).
encoding: str
Encoding to be used for decoding the conten... | 3.42362 | 3.804889 | 0.899795 |
documents = []
div_type = soup.get('type', None)
div_title = list(soup.children)[0].string.strip()
if div_type in target:
div_authors = soup.find_all('author')
document = {
'type': div_type,
'title': div_title,
'paragraphs': parse_paragraphs(... | def parse_div(soup, metadata, target) | Parse a <div> tag from the file.
The sections in XML files are given in <div1>, <div2> and <div3>
tags. Each such tag has a type and name (plus possibly more extra attributes).
If the div type is found in target variable, the div is parsed
into structured paragraphs, sentences and words.
... | 2.493209 | 2.524111 | 0.987757 |
paragraphs = []
for para in soup.find_all('p'):
sentences = []
for sent in para.find_all('s'):
sentence = sent.text.strip()
if len(sentence) > 0:
sentences.append(sentence)
if len(sentences) > 0:
paragraphs.append({'sentences': sen... | def parse_paragraphs(soup) | Parse sentences and paragraphs in the section.
Parameters
----------
soup: bs4.BeautifulSoup
The parsed XML data.
Returns
-------
list of (list of str)
List of paragraphs given as list of sentences. | 1.80231 | 2.173346 | 0.829279 |
sep = '\n\n'
texts = []
for doc in docs:
text = '\n\n'.join(['\n'.join(para[SENTENCES]) for para in doc[PARAGRAPHS]])
doc[TEXT] = text
del doc[PARAGRAPHS]
texts.append(Text(doc))
return texts | def tokenize_documents(docs) | Convert the imported documents to :py:class:'~estnltk.text.Text' instances. | 3.616071 | 3.225907 | 1.120947 |
docs = read_json_corpus(DEFAULT_NER_DATASET)
trainer = NerTrainer(default_nersettings)
trainer.train(docs, DEFAULT_NER_MODEL_DIR) | def train_default_model() | Function for training the default NER model.
NB! It overwrites the default model, so do not use it unless
you know what are you doing.
The training data is in file estnltk/corpora/estner.json.bz2 .
The resulting model will be saved to estnltk/estner/models/default.bin | 9.554861 | 8.669349 | 1.102143 |
def process_line(self, line):
assert isinstance(line, str)
try:
self._process.stdin.write(as_binary(line))
self._process.stdin.write(as_binary('\n'))
self._process.stdin.flush()
result = as_unicode(self._process.stdout.readline())
... | Process a line of data.
Sends the data through the pipe to the process and flush it. Reads a resulting line
and returns it.
Parameters
----------
line: str
The data sent to process. Make sure it does not contain any newline characte... | null | null | null | |
offsets = {}
current_seeked_offset_idx = 0
ordered_synset_idxes = sorted(synset_idxes)
with codecs.open(_SOI,'rb', 'utf-8') as fin:
for line in fin:
split_line = line.split(':')
while current_seeked_offset_idx < len(ordered_synset_idxes) and split_line[0... | def _get_synset_offsets(synset_idxes) | Returs pointer offset in the WordNet file for every synset index.
Notes
-----
Internal function. Do not call directly.
Preserves order -- for [x,y,z] returns [offset(x),offset(y),offset(z)].
Parameters
----------
synset_idxes : list of ints
Lists synset IDs, which need offset.
... | 3.134429 | 3.255229 | 0.962891 |
global parser
if parser is None:
parser = Parser(_WN_FILE)
synsets = []
for offset in synset_offsets:
raw_synset = parser.parse_synset(offset)
synset = Synset(raw_synset)
SYNSETS_DICT[_get_key_from_raw_synset(raw_synset)] = synset
SYNSETS_DICT[synset.id] = ... | def _get_synsets(synset_offsets) | Given synset offsets in the WordNet file, parses synset object for every offset.
Notes
-----
Internal function. Do not call directly.
Stores every parsed synset into global synset dictionary under two keys:
synset's name lemma.pos.sense_no and synset's id (unique integer).
Parameters
---... | 3.247719 | 3.383431 | 0.959889 |
pos = raw_synset.pos
literal = raw_synset.variants[0].literal
sense = "%02d"%raw_synset.variants[0].sense
return '.'.join([literal,pos,sense]) | def _get_key_from_raw_synset(raw_synset) | Derives synset key in the form of `lemma.pos.sense_no` from the provided eurown.py Synset class,
Notes
-----
Internal function. Do not call directly.
Parameters
----------
raw_synset : eurown.Synset
Synset representation from which lemma, part-of-speech and sense is derived.
Return... | 5.92749 | 5.348832 | 1.108184 |
if synset_key in SYNSETS_DICT:
return SYNSETS_DICT[synset_key]
def _get_synset_idx(synset_key):
with codecs.open(_SENSE_FILE,'rb', 'utf-8') as fin:
for line in fin:
split_line = line.split(':')
if split_line[0] == synset_key:
... | def synset(synset_key) | Returns synset object with the provided key.
Notes
-----
Uses lazy initialization - synsets will be fetched from a dictionary after the first request.
Parameters
----------
synset_key : string
Unique synset identifier in the form of `lemma.pos.sense_no`.
Returns
-------
... | 2.520475 | 2.599898 | 0.969452 |
def _get_synset_idxes(lemma,pos):
line_prefix_regexp = "%s:%s:(.*)"%(lemma,pos if pos else "\w+")
line_prefix = re.compile(line_prefix_regexp)
idxes = []
with codecs.open(_LIT_POS_FILE,'rb', 'utf-8') as fin:
for line in fin:
result = line_prefix.m... | def synsets(lemma,pos=None) | Returns all synset objects which have lemma as one of the variant literals and fixed pos, if provided.
Notes
-----
Uses lazy initialization - parses only those synsets which are not yet initialized, others are fetched from a dictionary.
Parameters
----------
lemma : str
Lemma of the syns... | 2.311126 | 2.33105 | 0.991453 |
def _get_unique_synset_idxes(pos):
idxes = []
with codecs.open(_LIT_POS_FILE,'rb', 'utf-8') as fin:
if pos == None:
for line in fin:
split_line = line.strip().split(':')
idxes.extend([int(x) for x in split_line[2].split()])
... | def all_synsets(pos=None) | Return all the synsets which have the provided pos.
Notes
-----
Returns thousands or tens of thousands of synsets - first time will take significant time.
Useful for initializing synsets as each returned synset is also stored in a global dictionary for fast retrieval the next time.
Parameters
... | 2.431928 | 2.458366 | 0.989246 |
if lemma_key in LEMMAS_DICT:
return LEMMAS_DICT[lemma_key]
split_lemma_key = lemma_key.split('.')
synset_key = '.'.join(split_lemma_key[:3])
lemma_literal = split_lemma_key[3]
lemma_obj = Lemma(synset_key,lemma_literal)
LEMMAS_DICT[lemma_key] = lemma_obj
return lemma_obj | def lemma(lemma_key) | Returns the Lemma object with the given key.
Parameters
----------
lemma_key : str
Key of the returned lemma.
Returns
-------
Lemma
Lemma matching the `lemma_key`. | 2.574268 | 2.855635 | 0.901469 |
lemma = lemma.lower()
return [lemma_obj
for synset in synsets(lemma,pos)
for lemma_obj in synset.lemmas()
if lemma_obj.name.lower() == lemma] | def lemmas(lemma,pos=None) | Returns all the Lemma objects of which name is `lemma` and which have `pos` as part
of speech.
Parameters
----------
lemma : str
Literal of the sought Lemma objects.
pos : str, optional
Part of speech of the sought Lemma objects. If None, matches any part of speech.
Defaults to No... | 3.431305 | 4.49106 | 0.76403 |
hypernyms |= synset._recursive_hypernyms(hypernyms)
return hypernyms | def _recursive_hypernyms(self, hypernyms):
hypernyms |= set(self.hypernyms())
for synset in self.hypernyms() | Finds all the hypernyms of the synset transitively.
Notes
-----
Internal method. Do not call directly.
Parameters
----------
hypernyms : set of Synsets
An set of hypernyms met so far.
Returns
-------
set of Synsets
Returns ... | 4.533209 | 9.65058 | 0.469734 |
if "min_depth" in self.__dict__:
return self.__dict__["min_depth"]
min_depth = 0
hypernyms = self.hypernyms()
if hypernyms:
min_depth = 1 + min(h._min_depth() for h in hypernyms)
self.__dict__["min_depth"] = min_depth
return min_depth | def _min_depth(self) | Finds minimum path length from the root.
Notes
-----
Internal method. Do not call directly.
Returns
-------
int
Minimum path length from the root. | 2.493835 | 2.708141 | 0.920866 |
results = []
for relation_candidate in self._raw_synset.internalLinks:
if relation_candidate.name == relation:
linked_synset = synset(_get_key_from_raw_synset(relation_candidate.target_concept))
relation_candidate.target_concept = linked_synset._raw_... | def get_related_synsets(self,relation) | Retrieves all the synsets which are related by given relation.
Parameters
----------
relation : str
Name of the relation via which the sought synsets are linked.
Returns
-------
list of Synsets
Synsets which are related via `relation`. | 5.03409 | 5.507398 | 0.91406 |
ancestor_depth = unvisited_ancestors.pop()
if ancestor_depth[1] > depth:
continue
unvisited_ancestors.extend([(synset,ancestor_depth[1]+1) for synset in ancestor_depth[0].get_related_synsets(relation)])
ancestors.append(ancestor_depth[0])
retu... | def closure(self, relation, depth=float('inf')):
ancestors = []
unvisited_ancestors = [(synset,1) for synset in self.get_related_synsets(relation)]
while len(unvisited_ancestors) > 0 | Finds all the ancestors of the synset using provided relation.
Parameters
----------
relation : str
Name of the relation which is recursively used to fetch the ancestors.
Returns
-------
list of Synsets
Returns the ancestors of the synset via given r... | 2.945737 | 3.339124 | 0.882188 |
visited = set()
hypernyms_next_level = set(self.hypernyms())
current_hypernyms = set(hypernyms_next_level)
while len(hypernyms_next_level) > 0:
current_hypernyms = set(hypernyms_next_level)
hypernyms_next_level = set()
for synset i... | def root_hypernyms(self) | Retrieves all the root hypernyms.
Returns
-------
list of Synsets
Roots via hypernymy relation. | 2.131793 | 2.161979 | 0.986038 |
if self._raw_synset.pos != synset._raw_synset.pos:
return None
depth = MAX_TAXONOMY_DEPTHS[self._raw_synset.pos]
distance = self._shortest_path_distance(synset)
if distance >= 0:
return -math.log((distance + 1) / (2.0 * depth))
else: ... | def lch_similarity(self, synset) | Calculates Leacock and Chodorow's similarity between the two synsets.
Notes
-----
Similarity is calculated using the formula -log( (dist(synset1,synset2)+1) / (2*maximum taxonomy depth) ).
Parameters
----------
synset : Synset
Synset from which the similarit... | 5.068255 | 3.819678 | 1.32688 |
lchs = self.lowest_common_hypernyms(target_synset)
lcs_depth = lchs[0]._min_depth() if lchs and len(lchs) else None
self_depth = self._min_depth()
other_depth = target_synset._min_depth()
if lcs_depth is None or self_depth is None or other_depth is None:
re... | def wup_similarity(self, target_synset) | Calculates Wu and Palmer's similarity between the two synsets.
Notes
-----
Similarity is calculated using the formula ( 2*depth(least_common_subsumer(synset1,synset2)) ) / ( depth(synset1) + depth(synset2) )
Parameters
----------
synset : Synset
... | 3.443172 | 3.389496 | 1.015836 |
return '\n'.join([variant.gloss for variant in self._raw_synset.variants if variant.gloss]) | def definition(self) | Returns the definition of the synset.
Returns
-------
str
Definition of the synset as a new-line separated concatenated string from all its variants' definitions. | 20.853884 | 8.643259 | 2.412734 |
examples = []
for example in [variant.examples for variant in self._raw_synset.variants if len(variant.examples)]:
examples.extend(example)
return examples | def examples(self) | Returns the examples of the synset.
Returns
-------
list of str
List of its variants' examples. | 7.579453 | 4.6026 | 1.646776 |
return [lemma("%s.%s"%(self.name,variant.literal)) for variant in self._raw_synset.variants] | def lemmas(self) | Returns the synset's lemmas/variants' literal represantions.
Returns
-------
list of Lemmas
List of its variations' literals as Lemma objects. | 19.065947 | 11.639141 | 1.638089 |
self_hypernyms = self._recursive_hypernyms(set())
other_hypernyms = target_synset._recursive_hypernyms(set())
common_hypernyms = self_hypernyms.intersection(other_hypernyms)
annot_common_hypernyms = [(hypernym, hypernym._min_depth()) for hypernym in common_hypernyms]
... | def lowest_common_hypernyms(self,target_synset) | Returns the common hypernyms of the synset and the target synset, which are furthest from the closest roots.
Parameters
----------
target_synset : Synset
Synset with which the common hypernyms are sought.
Returns
-------
list of Synsets
... | 2.136561 | 2.230781 | 0.957763 |
return synset('%s.%s.%s.%s'%(self.synset_literal,self.synset_pos,self.synset_sense,self.literal)) | def synset(self) | Returns synset into which the given lemma belongs to.
Returns
-------
Synset
Synset into which the given lemma belongs to. | 7.167572 | 7.332563 | 0.977499 |
''' Converts from vabamorf's JSON output, given as dict, into pre-syntactic mrf
format, given as a list of lines, as in the output of etmrf.
The aimed format looks something like this:
<s>
Kolmandaks
kolmandaks+0 //_D_ //
kolmas+ks //_O_ sg tr //
kih... | def convert_vm_json_to_mrf( vabamorf_json ) | Converts from vabamorf's JSON output, given as dict, into pre-syntactic mrf
format, given as a list of lines, as in the output of etmrf.
The aimed format looks something like this:
<s>
Kolmandaks
kolmandaks+0 //_D_ //
kolmas+ks //_O_ sg tr //
kihutas
... | 7.198717 | 3.318348 | 2.169368 |
''' Converts from Text object into pre-syntactic mrf format, given as a list of
lines, as in the output of etmrf.
*) If the input Text has already been morphologically analysed, uses the existing
analysis;
*) If the input has not been analysed, performs the analysis with require... | def convert_Text_to_mrf( text ) | Converts from Text object into pre-syntactic mrf format, given as a list of
lines, as in the output of etmrf.
*) If the input Text has already been morphologically analysed, uses the existing
analysis;
*) If the input has not been analysed, performs the analysis with required settin... | 9.209191 | 5.747602 | 1.602267 |
''' Loads rules that can be used to convert from Filosoft's mrf format to
syntactic analyzer's format. Returns a dict containing rules.
Expects that each line in the input file contains a single rule, and that
different parts of the rule separated by @ symbols, e.g.
1... | def load_fs_mrf_to_syntax_mrf_translation_rules( rulesFile ) | Loads rules that can be used to convert from Filosoft's mrf format to
syntactic analyzer's format. Returns a dict containing rules.
Expects that each line in the input file contains a single rule, and that
different parts of the rule separated by @ symbols, e.g.
1@_S_ ?@S... | 10.488853 | 1.419205 | 7.390653 |
''' Converts given analysis line if it describes punctuation; Uses the set
of predefined punctuation conversion rules from _punctConversions;
_punctConversions should be a list of lists, where each outer list stands
for a single conversion rule and inner list contains a pair of el... | def _convert_punctuation( line ) | Converts given analysis line if it describes punctuation; Uses the set
of predefined punctuation conversion rules from _punctConversions;
_punctConversions should be a list of lists, where each outer list stands
for a single conversion rule and inner list contains a pair of elements:
... | 10.049456 | 1.754401 | 5.72814 |
''' Converts given lines from Filosoft's mrf format to syntactic analyzer's
format, using the morph-category conversion rules from conversion_rules,
and punctuation via method _convert_punctuation();
As a result of conversion, the input list mrf_lines will be modified,
and also re... | def convert_mrf_to_syntax_mrf( mrf_lines, conversion_rules ) | Converts given lines from Filosoft's mrf format to syntactic analyzer's
format, using the morph-category conversion rules from conversion_rules,
and punctuation via method _convert_punctuation();
As a result of conversion, the input list mrf_lines will be modified,
and also returned a... | 4.57232 | 2.186316 | 2.091335 |
''' Converts pronouns (analysis lines with '_P_') from Filosoft's mrf to
syntactic analyzer's mrf format;
Uses the set of predefined pronoun conversion rules from _pronConversions;
_pronConversions should be a list of lists, where each outer list stands
for a single conver... | def convert_pronouns( mrf_lines ) | Converts pronouns (analysis lines with '_P_') from Filosoft's mrf to
syntactic analyzer's mrf format;
Uses the set of predefined pronoun conversion rules from _pronConversions;
_pronConversions should be a list of lists, where each outer list stands
for a single conversion rul... | 7.421958 | 1.843983 | 4.02496 |
''' Removes duplicate analysis lines from mrf_lines.
Uses special logic for handling adposition analyses ('_K_ pre' && '_K_ post')
that do not have subcategorization information:
*) If a word has both adposition analyses, removes '_K_ pre';
*) If a word has '_K_ post', re... | def remove_duplicate_analyses( mrf_lines, allow_to_delete_all = True ) | Removes duplicate analysis lines from mrf_lines.
Uses special logic for handling adposition analyses ('_K_ pre' && '_K_ post')
that do not have subcategorization information:
*) If a word has both adposition analyses, removes '_K_ pre';
*) If a word has '_K_ post', removes it... | 4.655549 | 2.298738 | 2.025263 |
''' Augments analysis lines with various hashtag information:
*) marks words with capital beginning with #cap;
*) marks finite verbs with #FinV;
*) marks nud/tud/mine/nu/tu/v/tav/mata/ja forms;
Hashtags are added at the end of the analysis content (just before the
last... | def add_hashtag_info( mrf_lines ) | Augments analysis lines with various hashtag information:
*) marks words with capital beginning with #cap;
*) marks finite verbs with #FinV;
*) marks nud/tud/mine/nu/tu/v/tav/mata/ja forms;
Hashtags are added at the end of the analysis content (just before the
last '//');
... | 9.031023 | 2.773903 | 3.25571 |
''' Loads subcategorization rules (for verbs and adpositions) from a text
file.
It is expected that the rules are given as pairs, where the first item is
the lemma (of verb/adposition), followed on the next line by the
subcategorization rule, in the following form:
... | def load_subcat_info( subcat_lex_file ) | Loads subcategorization rules (for verbs and adpositions) from a text
file.
It is expected that the rules are given as pairs, where the first item is
the lemma (of verb/adposition), followed on the next line by the
subcategorization rule, in the following form:
o... | 8.013127 | 1.710586 | 4.684434 |
''' Adds subcategorization information (hashtags) to verbs and adpositions;
Argument subcat_rules must be a dict containing subcategorization information,
loaded via method load_subcat_info();
Performs word lemma lookups in subcat_rules, and in case of a match, checks
word... | def tag_subcat_info( mrf_lines, subcat_rules ) | Adds subcategorization information (hashtags) to verbs and adpositions;
Argument subcat_rules must be a dict containing subcategorization information,
loaded via method load_subcat_info();
Performs word lemma lookups in subcat_rules, and in case of a match, checks
word part-of... | 5.693232 | 3.221859 | 1.767064 |
''' Converts given mrf lines from syntax preprocessing format to cg3 input
format:
*) surrounds words/tokens with "< and >"
*) surrounds word lemmas with " in analysis;
*) separates word endings from lemmas in analysis, and adds prefix 'L';
*) removes '//' and '//' fr... | def convert_to_cg3_input( mrf_lines ) | Converts given mrf lines from syntax preprocessing format to cg3 input
format:
*) surrounds words/tokens with "< and >"
*) surrounds word lemmas with " in analysis;
*) separates word endings from lemmas in analysis, and adds prefix 'L';
*) removes '//' and '//' from analy... | 5.64413 | 3.097444 | 1.82219 |
''' Executes the preprocessing pipeline on vabamorf's JSON, given as a dict;
Returns a list: lines of analyses in the VISL CG3 input format;
'''
mrf_lines = convert_vm_json_to_mrf( json_dict )
return self.process_mrf_lines( mrf_lines, **kwargs ) | def process_vm_json( self, json_dict, **kwargs ) | Executes the preprocessing pipeline on vabamorf's JSON, given as a dict;
Returns a list: lines of analyses in the VISL CG3 input format; | 21.729136 | 2.660294 | 8.167944 |
''' Executes the preprocessing pipeline on estnltk's Text object.
Returns a list: lines of analyses in the VISL CG3 input format;
'''
mrf_lines = convert_Text_to_mrf( text )
return self.process_mrf_lines( mrf_lines, **kwargs ) | def process_Text( self, text, **kwargs ) | Executes the preprocessing pipeline on estnltk's Text object.
Returns a list: lines of analyses in the VISL CG3 input format; | 26.436394 | 3.25086 | 8.132123 |
''' Executes the preprocessing pipeline on mrf_lines.
The input should be an analysis of the text in Filosoft's old mrf format;
Returns the input list, where elements (tokens/analyses) have been converted
into the new format;
'''
converted1 = convert_mrf_to_... | def process_mrf_lines( self, mrf_lines, **kwargs ) | Executes the preprocessing pipeline on mrf_lines.
The input should be an analysis of the text in Filosoft's old mrf format;
Returns the input list, where elements (tokens/analyses) have been converted
into the new format; | 6.812563 | 3.220235 | 2.115549 |
return [os.path.join(src_dir, fnm) for fnm in os.listdir(src_dir) if fnm.endswith(ending)] | def get_sources(src_dir='src', ending='.cpp') | Function to get a list of files ending with `ending` in `src_dir`. | 2.475784 | 2.366194 | 1.046315 |
def _get_ANSI_colored_font( color ):
''' Returns an ANSI escape code (a string) corresponding to switching the font
to given color, or None, if the given color could not be associated with
the available colors.
See also:
https://en.wikipedia.org/wiki/ANSI_escape_cod... | Returns an ANSI escape code (a string) corresponding to switching the font
to given color, or None, if the given color could not be associated with
the available colors.
See also:
https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
http://stackoverflow.com/q... | null | null | null | |
def _construct_end_index( spansStartingFrom ):
''' Creates an index which stores all annotations (from spansStartingFrom)
by their end position in text (annotation[END]).
Each start position (in the index) is associated with a list of
annotation objects (annotations ending at that... | Creates an index which stores all annotations (from spansStartingFrom)
by their end position in text (annotation[END]).
Each start position (in the index) is associated with a list of
annotation objects (annotations ending at that position).
An annotation object is also a list... | null | null | null | |
def _fix_overlapping_graphics( spansStartingFrom ):
''' Provides a fix for overlapping annotations that are formatted graphically
(underlined or printed in non-default color).
If two graphically formatted annotations overlap, and if one annotation,
say A, ends within another an... | Provides a fix for overlapping annotations that are formatted graphically
(underlined or printed in non-default color).
If two graphically formatted annotations overlap, and if one annotation,
say A, ends within another annotation, say B, then ending of graphics of A
also c... | null | null | null | |
def tprint( text, layers, markup_settings = None ):
''' Formats given text, adding a special ( ANSI-terminal compatible ) markup
to the annotations of given layers, and prints the formatted text to the
screen.
*) layers is a list containing names of the layers to be preformatted in
... | Formats given text, adding a special ( ANSI-terminal compatible ) markup
to the annotations of given layers, and prints the formatted text to the
screen.
*) layers is a list containing names of the layers to be preformatted in
the text (these layers must be present in Text);
... | null | null | null | |
css_prop = AES_CSS_MAP[aes_name]
if isinstance(css_value, list):
return get_mark_css_for_rules(aes_name, css_prop, css_value)
else:
return get_mark_simple_css(aes_name, css_prop, css_value) | def get_mark_css(aes_name, css_value) | Generate CSS class for <mark> tag.
Parameters
----------
aes_name: str
The name of the class.
css_value: str
The value for the CSS property defined by aes_name.
Returns
-------
list of str
The CSS codeblocks | 2.994716 | 4.027111 | 0.743639 |
def _loadSubcatRelations( self, inputFile ):
''' Laeb sisendfailist (inputFile) verb-nom/adv-vinf rektsiooniseoste mustrid.
Iga muster peab olema failis eraldi real, kujul:
(verbikirjeldus)\TAB(nom/adv-kirjeldus)\TAB(vinfkirjeldus)
nt
leid NEG aeg;S;(... | Laeb sisendfailist (inputFile) verb-nom/adv-vinf rektsiooniseoste mustrid.
Iga muster peab olema failis eraldi real, kujul:
(verbikirjeldus)\TAB(nom/adv-kirjeldus)\TAB(vinfkirjeldus)
nt
leid NEG aeg;S;((sg|pl) (p)|adt) da
leid POS võimalus;S;(... | null | null | null | |
def tokenMatchesNomAdvVinf( self, token, verb, vinf):
''' Teeb kindlaks, kas etteantud token v6iks olla verb'i alluv ning vinf'i ylemus (st
paikneda nende vahel). Kui see nii on, tagastab j2rjendi vahele sobiva s6na morf
analyysidega (meetodi _getMatchingAnalysisIDs abil), vastasel ... | Teeb kindlaks, kas etteantud token v6iks olla verb'i alluv ning vinf'i ylemus (st
paikneda nende vahel). Kui see nii on, tagastab j2rjendi vahele sobiva s6na morf
analyysidega (meetodi _getMatchingAnalysisIDs abil), vastasel juhul tagastab tyhja
j2rjendi; | null | null | null | |
def extendChainsInSentence( self, sentence, foundChains ):
''' Rakendab meetodit self.extendChainsInClause() antud lause igal osalausel.
'''
# 1) Preprocessing
clauses = getClausesByClauseIDs( sentence )
# 2) Extend verb chains in each clause
allDetectedVerbChains... | Rakendab meetodit self.extendChainsInClause() antud lause igal osalausel. | null | null | null | |
def _canBeExpanded( self, headVerbRoot, headVerbWID, suitableNomAdvExpansions, expansionVerbs, widToToken ):
''' Teeb kindlaks, kas kontekst on verbiahela laiendamiseks piisavalt selge/yhene:
1) Nii 'nom/adv' kandidaate kui ka Vinf kandidaate on täpselt üks;
2) Nom/adv ei kuulu mi... | Teeb kindlaks, kas kontekst on verbiahela laiendamiseks piisavalt selge/yhene:
1) Nii 'nom/adv' kandidaate kui ka Vinf kandidaate on täpselt üks;
2) Nom/adv ei kuulu mingi suurema fraasi kooseisu (meetodi _isLikelyNotPhrase() abil);
Kui tingimused täidetud, tagastab lisatava v... | null | null | null | |
textStart = 0
#Split the text in sections. Hackish part, but seems to work fine.
entries = re.split("\n=", text[textStart:])
stack = [[]]
intro = {}
sectionTitleRegEx = re.compile(r'={1,}.+={2,}')
section = {}
section['text'] = entries[0]
counts = []
#Presumes the first s... | def sectionsParser(text) | :param text: the whole text of an wikipedia article
:return: a list of nested section objects
[{title: "Rahvaarv",
text: "Eestis elab..."},
{title: "Ajalugu",
text: "..."},
sections: [{title: "Rahvaarv",
text: "Eestis elab..."},
... | 5.729589 | 5.583734 | 1.026121 |
return ''.join([c for c in text if c in self.alphabet]) | def clean(self, text) | Remove all unwanted characters from text. | 5.254635 | 4.380015 | 1.199684 |
return ''.join(sorted(set([c for c in text if c not in self.alphabet]))) | def invalid_characters(self, text) | Give simple list of invalid characters present in text. | 5.494483 | 4.417948 | 1.243673 |
result = defaultdict(list)
for idx, char in enumerate(text):
if char not in self.alphabet:
start = max(0, idx-context_size)
end = min(len(text), idx+context_size)
result[char].append(text[start:end])
return result | def find_invalid_chars(self, text, context_size=20) | Find invalid characters in text and store information about
the findings.
Parameters
----------
context_size: int
How many characters to return as the context. | 2.361109 | 2.75283 | 0.857702 |
result = defaultdict(list)
for text in texts:
for char, examples in self.find_invalid_chars(text, context_size).items():
result[char].extend(examples)
return result | def compute_report(self, texts, context_size=10) | Compute statistics of invalid characters on given texts.
Parameters
----------
texts: list of str
The texts to search for invalid characters.
context_size: int
How many characters to return as the context.
Returns
-------
dict of (char ->... | 4.39242 | 3.654628 | 1.201879 |
result = list(self.compute_report(texts, context_size).items())
result.sort(key=lambda x: (len(x[1]), x[0]), reverse=True)
s = 'Analyzed {0} texts.\n'.format(len(texts))
if (len(texts)) == 0:
f.write(s)
return
if len(result) > 0:
s +=... | def report(self, texts, n_examples=10, context_size=10, f=sys.stdout) | Compute statistics of invalid characters and print them.
Parameters
----------
texts: list of str
The texts to search for invalid characters.
n_examples: int
How many examples to display per invalid character.
context_size: int
How many charac... | 2.707346 | 2.603886 | 1.039733 |
''' Filters the dict of *kwargs*, keeping only arguments
whose keys are in *keep_list* and discarding all other
arguments.
Based on the filtring, constructs and returns a new
dict.
'''
new_kwargs = {}
for argName, argVal in k... | def _filter_kwargs(self, keep_list, **kwargs) | Filters the dict of *kwargs*, keeping only arguments
whose keys are in *keep_list* and discarding all other
arguments.
Based on the filtring, constructs and returns a new
dict. | 6.08593 | 2.007453 | 3.031668 |
''' Augments given Text object with the syntactic information
from the *text_layer*. More specifically, adds information
about SYNTAX_LABEL, SYNTAX_HEAD and DEPREL to each token
in the Text object;
(!) Note: this method is added to provide some ini... | def _augment_text_w_syntactic_info( self, text, text_layer ) | Augments given Text object with the syntactic information
from the *text_layer*. More specifically, adds information
about SYNTAX_LABEL, SYNTAX_HEAD and DEPREL to each token
in the Text object;
(!) Note: this method is added to provide some initial
... | 7.84227 | 3.832631 | 2.046185 |
''' Rewrites dependency links in the text from sentence-based linking to clause-
based linking:
*) words which have their parent outside-the-clause will become root
nodes (will obtain link value -1), and
*) words which have their parent inside-the-clause will have parent... | def _create_clause_based_dep_links( orig_text, layer=LAYER_CONLL ) | Rewrites dependency links in the text from sentence-based linking to clause-
based linking:
*) words which have their parent outside-the-clause will become root
nodes (will obtain link value -1), and
*) words which have their parent inside-the-clause will have parent index
... | 5.572063 | 3.552166 | 1.568638 |
''' Sorts analysis of all the words in the sentence.
This is required for consistency, because by default, analyses are
listed in arbitrary order; '''
for word in sentence:
if ANALYSIS not in word:
raise Exception( '(!) Error: no analysis found from word: '+str(word) )
... | def __sort_analyses(sentence) | Sorts analysis of all the words in the sentence.
This is required for consistency, because by default, analyses are
listed in arbitrary order; | 7.892372 | 4.693582 | 1.681524 |
''' Converts given estnltk Text object into CONLL format and returns as a
string.
Uses given *feature_generator* to produce fields ID, FORM, LEMMA, CPOSTAG,
POSTAG, FEATS for each token.
Fields to predict (HEAD, DEPREL) will be left empty.
This method is used in preparing p... | def convert_text_to_CONLL( text, feature_generator ) | Converts given estnltk Text object into CONLL format and returns as a
string.
Uses given *feature_generator* to produce fields ID, FORM, LEMMA, CPOSTAG,
POSTAG, FEATS for each token.
Fields to predict (HEAD, DEPREL) will be left empty.
This method is used in preparing parsing &... | 6.073492 | 2.173155 | 2.79478 |
''' Executes Maltparser on given (CONLL-style) input string, and
returns the result. The result is an array of lines from Maltparser's
output.
Parameters
----------
input_string: string
input text in CONLL format;
maltparser_jar: string
... | def _executeMaltparser( input_string, maltparser_dir, maltparser_jar, model_name ) | Executes Maltparser on given (CONLL-style) input string, and
returns the result. The result is an array of lines from Maltparser's
output.
Parameters
----------
input_string: string
input text in CONLL format;
maltparser_jar: string
... | 3.082531 | 2.123948 | 1.451321 |
''' Loads syntactically annotated text from CONLL format input file and
returns as an array of tokens, where each token is represented as
an array in the format:
[sentenceID, wordID, tokenString, morphInfo, selfID, parentID]
If addDepRels == True, then the dependency relation la... | def loadCONLLannotations( in_file, addDepRels = False, splitIntoSentences = True ) | Loads syntactically annotated text from CONLL format input file and
returns as an array of tokens, where each token is represented as
an array in the format:
[sentenceID, wordID, tokenString, morphInfo, selfID, parentID]
If addDepRels == True, then the dependency relation label is a... | 4.643341 | 1.634114 | 2.841504 |
''' Loads CONLL format data from given input file, and creates
estnltk Text objects from the data, one Text per each
sentence. Returns a list of Text objects.
By default, applies estnltk's morphological analysis, clause
detection, and verb chain detection to each input sen... | def convertCONLLtoText( in_file, addDepRels = False, verbose = False, **kwargs ) | Loads CONLL format data from given input file, and creates
estnltk Text objects from the data, one Text per each
sentence. Returns a list of Text objects.
By default, applies estnltk's morphological analysis, clause
detection, and verb chain detection to each input sentence.
... | 5.711041 | 3.002967 | 1.9018 |
''' Augments given Text object with the information from Maltparser's output.
More specifically, adds information about SYNTAX_LABEL, SYNTAX_HEAD and
DEPREL to each token in the Text object;
'''
j = 0
for sentence in text.divide( layer=WORDS, by=SENTENCES ):
sentence = __sort_ana... | def augmentTextWithCONLLstr( conll_str_array, text ) | Augments given Text object with the information from Maltparser's output.
More specifically, adds information about SYNTAX_LABEL, SYNTAX_HEAD and
DEPREL to each token in the Text object; | 5.875077 | 4.029716 | 1.457938 |
''' Collects clause with index *clause_id* from given *sentence_text*.
Returns a pair (clause, isEmbedded), where:
*clause* is a list of word tokens in the clause;
*isEmbedded* is a bool indicating whether the clause is embedded;
'''
clause = []
isEmbedded = False
indices =... | def _get_clause_words( sentence_text, clause_id ) | Collects clause with index *clause_id* from given *sentence_text*.
Returns a pair (clause, isEmbedded), where:
*clause* is a list of word tokens in the clause;
*isEmbedded* is a bool indicating whether the clause is embedded; | 5.012431 | 2.841401 | 1.76407 |
''' Searches for quotation marks (both opening and closing) closest to
given location in sentence (given as word index *wid*);
If *fromRight == True* (default), searches from the right (all the
words having index greater than *wid*), otherwise, searches from the
left (all... | def _detect_quotes( sentence_text, wid, fromRight = True ) | Searches for quotation marks (both opening and closing) closest to
given location in sentence (given as word index *wid*);
If *fromRight == True* (default), searches from the right (all the
words having index greater than *wid*), otherwise, searches from the
left (all the wor... | 5.145335 | 2.06546 | 2.491133 |
''' Laeb sisendfailist (inputFile) kaassõnade rektsiooniseoste mustrid.
Iga muster peab olema failis eraldi real, kujul:
(sõnalemma);(sõnaliik);(post|pre);(nõutud_käänete_regexp)
nt
ees;_K_;post;g
eest;_K_;post;g
enne;_K_;pre;p
Tagastab laetud andm... | def _loadKSubcatRelations( inputFile ) | Laeb sisendfailist (inputFile) kaassõnade rektsiooniseoste mustrid.
Iga muster peab olema failis eraldi real, kujul:
(sõnalemma);(sõnaliik);(post|pre);(nõutud_käänete_regexp)
nt
ees;_K_;post;g
eest;_K_;post;g
enne;_K_;pre;p
Tagastab laetud andmed sõnas... | 7.507693 | 2.229981 | 3.366707 |
''' Given the adposition appearing in the sentence at the location i,
checks whether the adposition appears in the kSubCatRelsLexicon,
and if so, attempts to further detect whether the adposition is a
preposition or a postposition;
Returns a tuple (string, int), where the first it... | def _detectKsubcatRelType( sentence, i, kSubCatRelsLexicon ) | Given the adposition appearing in the sentence at the location i,
checks whether the adposition appears in the kSubCatRelsLexicon,
and if so, attempts to further detect whether the adposition is a
preposition or a postposition;
Returns a tuple (string, int), where the first item indic... | 4.579482 | 2.216672 | 2.065927 |
''' Attempts to detect all possible K subcategorization relations from
given sentence, using the heuristic method _detectKsubcatRelType();
Returns a dictionary of relations where the key corresponds to the
index of its parent node (the K node) and the value corresponds to
i... | def _detectPossibleKsubcatRelsFromSent( sentence, kSubCatRelsLexicon, reverseMapping = False ) | Attempts to detect all possible K subcategorization relations from
given sentence, using the heuristic method _detectKsubcatRelType();
Returns a dictionary of relations where the key corresponds to the
index of its parent node (the K node) and the value corresponds to
index of ... | 5.674182 | 2.581877 | 2.197697 |
''' Attempts to detect all possible K subcategorization relations from
given sentence, using the heuristic methods _detectKsubcatRelType()
and _detectPossibleKsubcatRelsFromSent();
Returns a dictionary where the keys correspond to token indices,
and values are grammatical f... | def _findKsubcatFeatures( sentence, kSubCatRelsLexicon, addFeaturesToK = True ) | Attempts to detect all possible K subcategorization relations from
given sentence, using the heuristic methods _detectKsubcatRelType()
and _detectPossibleKsubcatRelsFromSent();
Returns a dictionary where the keys correspond to token indices,
and values are grammatical features ... | 6.967932 | 2.96851 | 2.347282 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.