Dataset Viewer
code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
if self.id: self.id += idsuffix
if recursive:
for e in self:
try:
e.addidsuffix(idsuffix, recursive)
except Exception:
pass | def addidsuffix(self, idsuffix, recursive = True) | Appends a suffix to this element's ID, and optionally to all child IDs as well. There is sually no need to call this directly, invoked implicitly by :meth:`copy` | 3.406982 | 3.047689 | 1.11789 |
for c in self:
if isinstance(c, AbstractElement):
c.parent = self
c.setparents() | def setparents(self) | Correct all parent relations for elements within the scop. There is sually no need to call this directly, invoked implicitly by :meth:`copy` | 5.899053 | 4.490749 | 1.313601 |
self.doc = newdoc
if self.doc and self.id:
self.doc.index[self.id] = self
for c in self:
if isinstance(c, AbstractElement):
c.setdoc(newdoc) | def setdoc(self,newdoc) | Set a different document. Usually no need to call this directly, invoked implicitly by :meth:`copy` | 4.070186 | 3.677949 | 1.106645 |
return True
else:
try:
if strict:
self.textcontent(cls, correctionhandling) #will raise NoSuchTextException when not found
return True
else:
#Check children
for e in self:
if e.PRINTABLE and not isinstance(e, TextContent):
if e.hastext(cls, strict, correctionhandling):
return True
self.textcontent(cls, correctionhandling) #will raise NoSuchTextException when not found
return True
except NoSuchText:
return False | def hastext(self,cls='current',strict=True, correctionhandling=CorrectionHandling.CURRENT): #pylint: disable=too-many-return-statements
if not self.PRINTABLE: #only printable elements can hold text
return False
elif self.TEXTCONTAINER | Does this element have text (of the specified class)
By default, and unlike :meth:`text`, this checks strictly, i.e. the element itself must have the text and it is not inherited from its children.
Parameters:
cls (str): The class of the text content to obtain, defaults to ``current``.
strict (bool): Set this if you are strictly interested in the text explicitly associated with the element, without recursing into children. Defaults to ``True``.
correctionhandling: Specifies what text to check for when corrections are encountered. The default is ``CorrectionHandling.CURRENT``, which will retrieve the corrected/current text. You can set this to ``CorrectionHandling.ORIGINAL`` if you want the text prior to correction, and ``CorrectionHandling.EITHER`` if you don't care.
Returns:
bool | 4.143237 | 4.585317 | 0.903588 |
return True
else:
try:
if strict:
self.phoncontent(cls, correctionhandling)
return True
else:
#Check children
for e in self:
if e.SPEAKABLE and not isinstance(e, PhonContent):
if e.hasphon(cls, strict, correctionhandling):
return True
self.phoncontent(cls) #will raise NoSuchTextException when not found
return True
except NoSuchPhon:
return False | def hasphon(self,cls='current',strict=True,correctionhandling=CorrectionHandling.CURRENT): #pylint: disable=too-many-return-statements
if not self.SPEAKABLE: #only printable elements can hold text
return False
elif self.PHONCONTAINER | Does this element have phonetic content (of the specified class)
By default, and unlike :meth:`phon`, this checks strictly, i.e. the element itself must have the phonetic content and it is not inherited from its children.
Parameters:
cls (str): The class of the phonetic content to obtain, defaults to ``current``.
strict (bool): Set this if you are strictly interested in the phonetic content explicitly associated with the element, without recursing into children. Defaults to ``True``.
correctionhandling: Specifies what phonetic content to check for when corrections are encountered. The default is ``CorrectionHandling.CURRENT``, which will retrieve the corrected/current phonetic content. You can set this to ``CorrectionHandling.ORIGINAL`` if you want the phonetic content prior to correction, and ``CorrectionHandling.EITHER`` if you don't care.
Returns:
bool | 5.429063 | 5.362274 | 1.012455 |
self.replace(TextContent, value=text, cls=cls) | def settext(self, text, cls='current') | Set the text for this element.
Arguments:
text (str): The text
cls (str): The class of the text, defaults to ``current`` (leave this unless you know what you are doing). There may be only one text content element of each class associated with the element. | 17.233418 | 20.449476 | 0.842731 |
assert isinstance(doc, Document)
if not self.doc:
self.doc = doc
if self.id:
if self.id in doc:
raise DuplicateIDError(self.id)
else:
self.doc.index[id] = self
for e in self: #recursive for all children
if isinstance(e,AbstractElement): e.setdocument(doc) | def setdocument(self, doc) | Associate a document with this element.
Arguments:
doc (:class:`Document`): A document
Each element must be associated with a FoLiA document. | 5.460404 | 5.215816 | 1.046894 |
if not parent.__class__.accepts(Class, raiseexceptions, parent):
return False
if Class.OCCURRENCES > 0:
#check if the parent doesn't have too many already
count = parent.count(Class,None,True,[True, AbstractStructureElement]) #never descend into embedded structure annotatioton
if count >= Class.OCCURRENCES:
if raiseexceptions:
if parent.id:
extra = ' (id=' + parent.id + ')'
else:
extra = ''
raise DuplicateAnnotationError("Unable to add another object of type " + Class.__name__ + " to " + parent.__class__.__name__ + " " + extra + ". There are already " + str(count) + " instances of this class, which is the maximum.")
else:
return False
if Class.OCCURRENCES_PER_SET > 0 and set and Class.REQUIRED_ATTRIBS and Attrib.CLASS in Class.REQUIRED_ATTRIBS:
count = parent.count(Class,set,True, [True, AbstractStructureElement])
if count >= Class.OCCURRENCES_PER_SET:
if raiseexceptions:
if parent.id:
extra = ' (id=' + parent.id + ')'
else:
extra = ''
raise DuplicateAnnotationError("Unable to add another object of set " + set + " and type " + Class.__name__ + " to " + parent.__class__.__name__ + " " + extra + ". There are already " + str(count) + " instances of this class, which is the maximum for the set.")
else:
return False
return True | def addable(Class, parent, set=None, raiseexceptions=True) | Tests whether a new element of this class can be added to the parent.
This method is mostly for internal use.
This will use the ``OCCURRENCES`` property, but may be overidden by subclasses for more customised behaviour.
Parameters:
parent (:class:`AbstractElement`): The element that is being added to
set (str or None): The set
raiseexceptions (bool): Raise an exception if the element can't be added?
Returns:
bool
Raises:
ValueError | 3.576035 | 3.406295 | 1.049831 |
#If the element was not associated with a document yet, do so now (and for all unassociated children:
if not self.doc and self.parent.doc:
self.setdocument(self.parent.doc)
if self.doc and self.doc.deepvalidation:
self.deepvalidation() | def postappend(self) | This method will be called after an element is added to another and does some checks.
It can do extra checks and if necessary raise exceptions to prevent addition. By default makes sure the right document is associated.
This method is mostly for internal use. | 9.216802 | 6.786068 | 1.358195 |
if self.doc and self.doc.deepvalidation and self.set and self.set[0] != '_':
try:
self.doc.setdefinitions[self.set].testclass(self.cls)
except KeyError:
if self.cls and not self.doc.allowadhocsets:
raise DeepValidationError("Set definition " + self.set + " for " + self.XMLTAG + " not loaded!")
except DeepValidationError as e:
errormsg = str(e) + " (in set " + self.set+" for " + self.XMLTAG
if self.id:
errormsg += " with ID " + self.id
errormsg += ")"
raise DeepValidationError(errormsg) | def deepvalidation(self) | Perform deep validation of this element.
Raises:
:class:`DeepValidationError` | 5.420633 | 5.179882 | 1.046478 |
return list(parent.select(Class,set,False)) | def findreplaceables(Class, parent, set=None,**kwargs) | Internal method to find replaceable elements. Auxiliary function used by :meth:`AbstractElement.replace`. Can be overriden for more fine-grained control. | 14.125532 | 13.382312 | 1.055538 |
if self.TEXTCONTAINER:
s = ""
for child in self:
if isinstance(child, AbstractElement):
child.updatetext()
s += child.text()
elif isstring(child):
s += child
self.data = [s] | def updatetext(self) | Recompute textual value based on the text content of the children. Only supported on elements that are a ``TEXTCONTAINER`` | 6.820878 | 4.518931 | 1.509401 |
if 'set' in kwargs:
set = kwargs['set']
del kwargs['set']
else:
try:
set = child.set
except AttributeError:
set = None
if inspect.isclass(child):
Class = child
replace = Class.findreplaceables(self, set, **kwargs)
elif (self.TEXTCONTAINER or self.PHONCONTAINER) and isstring(child):
#replace will replace ALL text content, removing text markup along the way!
self.data = []
return self.append(child, *args,**kwargs)
else:
Class = child.__class__
kwargs['instance'] = child
replace = Class.findreplaceables(self,set,**kwargs)
del kwargs['instance']
kwargs['set'] = set #was deleted temporarily for findreplaceables
if len(replace) == 0:
#nothing to replace, simply call append
if 'alternative' in kwargs:
del kwargs['alternative'] #has other meaning in append()
return self.append(child, *args, **kwargs)
elif len(replace) > 1:
raise Exception("Unable to replace. Multiple candidates found, unable to choose.")
elif len(replace) == 1:
if 'alternative' in kwargs and kwargs['alternative']:
#old version becomes alternative
if replace[0] in self.data:
self.data.remove(replace[0])
alt = self.append(Alternative)
alt.append(replace[0])
del kwargs['alternative'] #has other meaning in append()
else:
#remove old version competely
self.remove(replace[0])
e = self.append(child, *args, **kwargs)
self.updatetext()
return e | def replace(self, child, *args, **kwargs) | Appends a child element like ``append()``, but replaces any existing child element of the same type and set. If no such child element exists, this will act the same as append()
Keyword arguments:
alternative (bool): If set to True, the *replaced* element will be made into an alternative. Simply use :meth:`AbstractElement.append` if you want the added element
to be an alternative.
See :meth:`AbstractElement.append` for more information and all parameters. | 5.118151 | 4.930508 | 1.038057 |
e = self
while e:
if e.parent:
e = e.parent
if not Class or isinstance(e,Class):
yield e
elif isinstance(Class, tuple):
for C in Class:
if isinstance(e,C):
yield e
else:
break | def ancestors(self, Class=None) | Generator yielding all ancestors of this element, effectively back-tracing its path to the root element. A tuple of multiple classes may be specified.
Arguments:
*Class: The class or classes (:class:`AbstractElement` or subclasses). Not instances!
Yields:
elements (instances derived from :class:`AbstractElement`) | 2.996542 | 3.448565 | 0.868924 |
for e in self.ancestors(tuple(Classes)):
return e
raise NoSuchAnnotation | def ancestor(self, *Classes) | Find the most immediate ancestor of the specified type, multiple classes may be specified.
Arguments:
*Classes: The possible classes (:class:`AbstractElement` or subclasses) to select from. Not instances!
Example::
paragraph = word.ancestor(folia.Paragraph) | 15.977091 | 64.94973 | 0.245992 |
jsonnode = {}
jsonnode['type'] = self.XMLTAG
if self.id:
jsonnode['id'] = self.id
if self.set:
jsonnode['set'] = self.set
if self.cls:
jsonnode['class'] = self.cls
if self.annotator:
jsonnode['annotator'] = self.annotator
if self.annotatortype:
if self.annotatortype == AnnotatorType.AUTO:
jsonnode['annotatortype'] = "auto"
elif self.annotatortype == AnnotatorType.MANUAL:
jsonnode['annotatortype'] = "manual"
if self.confidence is not None:
jsonnode['confidence'] = self.confidence
if self.n:
jsonnode['n'] = self.n
if self.auth:
jsonnode['auth'] = self.auth
if self.datetime:
jsonnode['datetime'] = self.datetime.strftime("%Y-%m-%dT%H:%M:%S")
if recurse: #pylint: disable=too-many-nested-blocks
jsonnode['children'] = []
if self.TEXTCONTAINER:
jsonnode['text'] = self.text()
if self.PHONCONTAINER:
jsonnode['phon'] = self.phon()
for child in self:
if self.TEXTCONTAINER and isstring(child):
jsonnode['children'].append(child)
elif not self.PHONCONTAINER:
#check ignore list
ignore = False
if ignorelist:
for e in ignorelist:
if isinstance(child,e):
ignore = True
break
if not ignore:
jsonnode['children'].append(child.json(attribs,recurse,ignorelist))
if attribs:
for attrib in attribs:
jsonnode[attrib] = attribs
return jsonnode | def json(self, attribs=None, recurse=True, ignorelist=False) | Serialises the FoLiA element and all its contents to a Python dictionary suitable for serialisation to JSON.
Example::
import json
json.dumps(word.json())
Returns:
dict | 2.362132 | 2.5199 | 0.937391 |
s = ElementTree.tostring(self.xml(), xml_declaration=False, pretty_print=pretty_print, encoding='utf-8')
if sys.version < '3':
if isinstance(s, str):
s = unicode(s,'utf-8') #pylint: disable=undefined-variable
else:
if isinstance(s,bytes):
s = str(s,'utf-8')
s = s.replace('ns0:','') #ugly patch to get rid of namespace prefix
s = s.replace(':ns0','')
return s | def xmlstring(self, pretty_print=False) | Serialises this FoLiA element and all its contents to XML.
Returns:
str: a string with XML representation for this element and all its children | 3.09494 | 3.36817 | 0.918879 |
# ignorelist = default_ignore
if not node:
node = self
for e in self.data: #pylint: disable=too-many-nested-blocks
if (not self.TEXTCONTAINER and not self.PHONCONTAINER) or isinstance(e, AbstractElement):
if ignore is True:
try:
if not e.auth:
continue
except AttributeError:
#not all elements have auth attribute..
pass
elif ignore: #list
doignore = False
for c in ignore:
if c is True:
try:
if not e.auth:
doignore =True
break
except AttributeError:
#not all elements have auth attribute..
pass
elif c == e.__class__ or issubclass(e.__class__,c):
doignore = True
break
if doignore:
continue
if isinstance(e, Class):
if not set is None:
try:
if e.set != set:
continue
except AttributeError:
continue
yield e
if recursive:
for e2 in e.select(Class, set, recursive, ignore, e):
if not set is None:
try:
if e2.set != set:
continue
except AttributeError:
continue
yield e2 | def select(self, Class, set=None, recursive=True, ignore=True, node=None): #pylint: disable=bad-classmethod-argument,redefined-builtin
#if ignorelist is True | Select child elements of the specified class.
A further restriction can be made based on set.
Arguments:
Class (class): The class to select; any python class (not instance) subclassed off :class:`AbstractElement`
Set (str): The set to match against, only elements pertaining to this set will be returned. If set to None (default), all elements regardless of set will be returned.
recursive (bool): Select recursively? Descending into child elements? Defaults to ``True``.
ignore: A list of Classes to ignore, if set to ``True`` instead of a list, all non-authoritative elements will be skipped (this is the default behaviour and corresponds to the following elements: :class:`Alternative`, :class:`AlternativeLayer`, :class:`Suggestion`, and :class:`folia.Original`. These elements and those contained within are never *authorative*. You may also include the boolean True as a member of a list, if you want to skip additional tags along the predefined non-authoritative ones.
* ``node``: Reserved for internal usage, used in recursion.
Yields:
Elements (instances derived from :class:`AbstractElement`)
Example::
for sense in text.select(folia.Sense, 'cornetto', True, [folia.Original, folia.Suggestion, folia.Alternative] ):
.. | 3.390967 | 3.40144 | 0.996921 |
return sum(1 for i in self.select(Class,set,recursive,ignore,node) ) | def count(self, Class, set=None, recursive=True, ignore=True, node=None) | Like :meth:`AbstractElement.select`, but instead of returning the elements, it merely counts them.
Returns:
int | 5.367037 | 6.376721 | 0.841661 |
if e not in founditems: #prevent going in recursive loops
l.append(e)
if isinstance(e, AbstractElement):
l += e.items(l)
return l | def items(self, founditems=[]): #pylint: disable=dangerous-default-value
l = []
for e in self.data | Returns a depth-first flat list of *all* items below this element (not limited to AbstractElement) | 10.073014 | 5.376596 | 1.873493 |
if self.metadata:
d = self.doc.submetadata[self.metadata]
elif self.parent:
d = self.parent.getmetadata()
elif self.doc:
d = self.doc.metadata
else:
return None
if key:
return d[key]
else:
return d | def getmetadata(self, key=None) | Get the metadata that applies to this element, automatically inherited from parent elements | 3.197786 | 3.00644 | 1.063645 |
#breadth first search
for i, c in enumerate(self.data):
if c is child:
return i
if recursive: #pylint: disable=too-many-nested-blocks
for i, c in enumerate(self.data):
if ignore is True:
try:
if not c.auth:
continue
except AttributeError:
#not all elements have auth attribute..
pass
elif ignore: #list
doignore = False
for e in ignore:
if e is True:
try:
if not c.auth:
doignore =True
break
except AttributeError:
#not all elements have auth attribute..
pass
elif e == c.__class__ or issubclass(c.__class__,e):
doignore = True
break
if doignore:
continue
if isinstance(c, AbstractElement):
j = c.getindex(child, recursive)
if j != -1:
return i #yes, i ... not j!
return -1 | def getindex(self, child, recursive=True, ignore=True) | Get the index at which an element occurs, recursive by default!
Returns:
int | 3.807518 | 3.919408 | 0.971452 |
try:
ancestor = next(commonancestors(AbstractElement, self, other))
except StopIteration:
raise Exception("Elements share no common ancestor")
#now we just do a depth first search and see who comes first
def callback(e):
if e is self:
return True
elif e is other:
return False
return None
result = ancestor.depthfirstsearch(callback)
if result is None:
raise Exception("Unable to find relation between elements! (shouldn't happen)")
return result | def precedes(self, other) | Returns a boolean indicating whether this element precedes the other element | 6.478656 | 6.419454 | 1.009222 |
result = function(self)
if result is not None:
return result
for e in self:
result = e.depthfirstsearch(function)
if result is not None:
return result
return None | def depthfirstsearch(self, function) | Generic depth first search algorithm using a callback function, continues as long as the callback function returns None | 2.276462 | 2.421214 | 0.940215 |
if Class is True: Class = self.__class__
if scope is True: scope = STRUCTURESCOPE
structural = Class is not None and issubclass(Class,AbstractStructureElement)
if reverse:
order = reversed
descendindex = -1
else:
order = lambda x: x #pylint: disable=redefined-variable-type
descendindex = 0
child = self
parent = self.parent
while parent: #pylint: disable=too-many-nested-blocks
if len(parent) > 1:
returnnext = False
for e in order(parent):
if e is child:
#we found the current item, next item will be the one to return
returnnext = True
elif returnnext and e.auth and not isinstance(e,AbstractAnnotationLayer) and (not structural or (structural and (not isinstance(e,(AbstractTokenAnnotation,TextContent)) ) )):
if structural and isinstance(e,Correction):
if not list(e.select(AbstractStructureElement)): #skip-over non-structural correction
continue
if Class is None or (isinstance(Class,tuple) and (any(isinstance(e,C) for C in Class))) or isinstance(e,Class):
return e
else:
#this is not yet the element of the type we are looking for, we are going to descend again in the very leftmost (rightmost if reversed) branch only
while e.data:
e = e.data[descendindex]
if not isinstance(e, AbstractElement):
return None #we've gone too far
if e.auth and not isinstance(e,AbstractAnnotationLayer):
if Class is None or (isinstance(Class,tuple) and (any(isinstance(e,C) for C in Class))) or isinstance(e,Class):
return e
else:
#descend deeper
continue
return None
#generational iteration
child = parent
if scope is not None and child.__class__ in scope:
#you shall not pass!
break
parent = parent.parent
return None | def next(self, Class=True, scope=True, reverse=False) | Returns the next element, if it is of the specified type and if it does not cross the boundary of the defined scope. Returns None if no next element is found. Non-authoritative elements are never returned.
Arguments:
* ``Class``: The class to select; any python class subclassed off `'AbstractElement``, may also be a tuple of multiple classes. Set to ``True`` to constrain to the same class as that of the current instance, set to ``None`` to not constrain at all
* ``scope``: A list of classes which are never crossed looking for a next element. Set to ``True`` to constrain to a default list of structure elements (Sentence,Paragraph,Division,Event, ListItem,Caption), set to ``None`` to not constrain at all. | 5.550529 | 5.39329 | 1.029155 |
return self.next(Class,scope, True) | def previous(self, Class=True, scope=True) | Returns the previous element, if it is of the specified type and if it does not cross the boundary of the defined scope. Returns None if no next element is found. Non-authoritative elements are never returned.
Arguments:
* ``Class``: The class to select; any python class subclassed off `'AbstractElement``. Set to ``True`` to constrain to the same class as that of the current instance, set to ``None`` to not constrain at all
* ``scope``: A list of classes which are never crossed looking for a next element. Set to ``True`` to constrain to a default list of structure elements (Sentence,Paragraph,Division,Event, ListItem,Caption), set to ``None`` to not constrain at all. | 16.407049 | 20.213709 | 0.811679 |
if size == 0: return [] #for efficiency
context = []
e = self
while len(context) < size:
e = e.previous(True,scope)
if not e: break
context.append(e)
if placeholder:
while len(context) < size:
context.append(placeholder)
context.reverse()
return context | def leftcontext(self, size, placeholder=None, scope=None) | Returns the left context for an element, as a list. This method crosses sentence/paragraph boundaries by default, which can be restricted by setting scope | 3.768129 | 3.911083 | 0.963449 |
if size == 0: return [] #for efficiency
context = []
e = self
while len(context) < size:
e = e.next(True,scope)
if not e: break
context.append(e)
if placeholder:
while len(context) < size:
context.append(placeholder)
return context | def rightcontext(self, size, placeholder=None, scope=None) | Returns the right context for an element, as a list. This method crosses sentence/paragraph boundaries by default, which can be restricted by setting scope | 3.896239 | 4.117546 | 0.946253 |
return self.leftcontext(size, placeholder,scope) + [self] + self.rightcontext(size, placeholder,scope) | def context(self, size, placeholder=None, scope=None) | Returns this word in context, {size} words to the left, the current word, and {size} words to the right | 5.708879 | 4.198796 | 1.359647 |
if not isinstance(child, AbstractElement):
raise ValueError("Expected AbstractElement, got " + str(type(child)))
if child.parent == self:
child.parent = None
self.data.remove(child)
#delete from index
if child.id and self.doc and child.id in self.doc.index:
del self.doc.index[child.id] | def remove(self, child) | Removes the child element | 3.498961 | 3.429381 | 1.020289 |
e = self.parent
while e:
if isinstance(e, Correction):
return e
if isinstance(e, AbstractStructureElement):
break
e = e.parent
return None | def incorrection(self) | Is this element part of a correction? If it is, it returns the Correction element (evaluating to True), otherwise it returns None | 6.742775 | 4.246475 | 1.587852 |
found = False
for e in self.select(Class,set,True,default_ignore_annotations):
found = True
yield e
if not found:
raise NoSuchAnnotation() | def annotations(self,Class,set=None) | Obtain child elements (annotations) of the specified class.
A further restriction can be made based on set.
Arguments:
Class (class): The class to select; any python class (not instance) subclassed off :class:`AbstractElement`
Set (str): The set to match against, only elements pertaining to this set will be returned. If set to None (default), all elements regardless of set will be returned.
Yields:
Elements (instances derived from :class:`AbstractElement`)
Example::
for sense in text.annotations(folia.Sense, 'http://some/path/cornetto'):
..
See also:
:meth:`AbstractElement.select`
Raises:
:meth:`AllowTokenAnnotation.annotations`
:class:`NoSuchAnnotation` if no such annotation exists | 8.737211 | 9.770823 | 0.894214 |
return sum( 1 for _ in self.select(Class,set,True,default_ignore_annotations)) | def hasannotation(self,Class,set=None) | Returns an integer indicating whether such as annotation exists, and if so, how many.
See :meth:`AllowTokenAnnotation.annotations`` for a description of the parameters. | 20.699705 | 19.898621 | 1.040258 |
for e in self.select(type,set,True,default_ignore_annotations):
return e
raise NoSuchAnnotation() | def annotation(self, type, set=None) | Obtain a single annotation element.
A further restriction can be made based on set.
Arguments:
Class (class): The class to select; any python class (not instance) subclassed off :class:`AbstractElement`
Set (str): The set to match against, only elements pertaining to this set will be returned. If set to None (default), all elements regardless of set will be returned.
Returns:
An element (instance derived from :class:`AbstractElement`)
Example::
sense = word.annotation(folia.Sense, 'http://some/path/cornetto').cls
See also:
:meth:`AllowTokenAnnotation.annotations`
:meth:`AbstractElement.select`
Raises:
:class:`NoSuchAnnotation` if no such annotation exists | 22.930361 | 25.307119 | 0.906083 |
e = super(AbstractStructureElement,self).append(child, *args, **kwargs)
self._setmaxid(e)
return e | def append(self, child, *args, **kwargs) | See ``AbstractElement.append()`` | 8.354598 | 6.256866 | 1.335269 |
if index is None:
return self.select(Word,None,True,default_ignore_structure)
else:
if index < 0:
index = self.count(Word,None,True,default_ignore_structure) + index
for i, e in enumerate(self.select(Word,None,True,default_ignore_structure)):
if i == index:
return e
raise IndexError | def words(self, index = None) | Returns a generator of Word elements found (recursively) under this element.
Arguments:
* ``index``: If set to an integer, will retrieve and return the n'th element (starting at 0) instead of returning the list of all | 3.84442 | 3.861558 | 0.995562 |
if index is None:
return self.select(Paragraph,None,True,default_ignore_structure)
else:
if index < 0:
index = self.count(Paragraph,None,True,default_ignore_structure) + index
for i,e in enumerate(self.select(Paragraph,None,True,default_ignore_structure)):
if i == index:
return e
raise IndexError | def paragraphs(self, index = None) | Returns a generator of Paragraph elements found (recursively) under this element.
Arguments:
index (int or None): If set to an integer, will retrieve and return the n'th element (starting at 0) instead of returning the generator of all | 3.556048 | 3.969901 | 0.895752 |
if index is None:
return self.select(Sentence,None,True,default_ignore_structure)
else:
if index < 0:
index = self.count(Sentence,None,True,default_ignore_structure) + index
for i,e in enumerate(self.select(Sentence,None,True,default_ignore_structure)):
if i == index:
return e
raise IndexError | def sentences(self, index = None) | Returns a generator of Sentence elements found (recursively) under this element
Arguments:
index (int or None): If set to an integer, will retrieve and return the n'th element (starting at 0) instead of returning a generator of all | 3.685321 | 3.748857 | 0.983052 |
if inspect.isclass(annotationtype): annotationtype = annotationtype.ANNOTATIONTYPE
return [ x for x in self.select(AbstractAnnotationLayer,set,False,True) if annotationtype is None or x.ANNOTATIONTYPE == annotationtype ] | def layers(self, annotationtype=None,set=None) | Returns a list of annotation layers found *directly* under this element, does not include alternative layers | 5.460087 | 5.369339 | 1.016901 |
l = self.layers(annotationtype, set)
return (len(l) > 0) | def hasannotationlayer(self, annotationtype=None,set=None) | Does the specified annotation layer exist? | 5.18264 | 4.500535 | 1.151561 |
if not attribs: attribs = {}
if self.idref:
attribs['id'] = self.idref
return super(AbstractTextMarkup,self).xml(attribs,elements, skipchildren) | def xml(self, attribs = None,elements = None, skipchildren = False) | See :meth:`AbstractElement.xml` | 4.502673 | 3.817091 | 1.179608 |
if not attribs: attribs = {}
if self.idref:
attribs['id'] = self.idref
return super(AbstractTextMarkup,self).json(attribs,recurse, ignorelist) | def json(self,attribs =None, recurse=True, ignorelist=False) | See :meth:`AbstractElement.json` | 4.466887 | 3.825315 | 1.167717 |
return super(TextContent,self).text(normalize_spaces=normalize_spaces) | def text(self, normalize_spaces=False) | Obtain the text (unicode instance) | 6.022126 | 5.933878 | 1.014872 |
if self.offset is None: return None #nothing to test
if self.ref:
ref = self.doc[self.ref]
else:
ref = self.finddefaultreference()
if not ref:
raise UnresolvableTextContent("Default reference for textcontent not found!")
elif not ref.hastext(self.cls):
raise UnresolvableTextContent("Reference (ID " + str(ref.id) + ") has no such text (class=" + self.cls+")")
elif validate and self.text() != ref.textcontent(self.cls).text()[self.offset:self.offset+len(self.data[0])]:
raise UnresolvableTextContent("Reference (ID " + str(ref.id) + ", class=" + self.cls+") found but no text match at specified offset ("+str(self.offset)+")! Expected '" + self.text() + "', got '" + ref.textcontent(self.cls).text()[self.offset:self.offset+len(self.data[0])] +"'")
else:
#finally, we made it!
return ref | def getreference(self, validate=True) | Returns and validates the Text Content's reference. Raises UnresolvableTextContent when invalid | 4.400683 | 3.993784 | 1.101883 |
attribs = {}
if not self.offset is None:
attribs['{' + NSFOLIA + '}offset'] = str(self.offset)
if self.parent and self.ref:
attribs['{' + NSFOLIA + '}ref'] = self.ref
#if self.cls != 'current' and not (self.cls == 'original' and any( isinstance(x, Original) for x in self.ancestors() ) ):
# attribs['{' + NSFOLIA + '}class'] = self.cls
#else:
# if '{' + NSFOLIA + '}class' in attribs:
# del attribs['{' + NSFOLIA + '}class']
#return E.t(self.value, **attribs)
e = super(TextContent,self).xml(attribs,elements,skipchildren)
if '{' + NSFOLIA + '}class' in e.attrib and e.attrib['{' + NSFOLIA + '}class'] == "current":
#delete 'class=current'
del e.attrib['{' + NSFOLIA + '}class']
return e | def xml(self, attribs = None,elements = None, skipchildren = False) | See :meth:`AbstractElement.xml` | 3.183361 | 3.134874 | 1.015467 |
if self.offset is None: return None #nothing to test
if self.ref:
ref = self.doc[self.ref]
else:
ref = self.finddefaultreference()
if not ref:
raise UnresolvableTextContent("Default reference for phonetic content not found!")
elif not ref.hasphon(self.cls):
raise UnresolvableTextContent("Reference has no such phonetic content (class=" + self.cls+")")
elif validate and self.phon() != ref.textcontent(self.cls).phon()[self.offset:self.offset+len(self.data[0])]:
raise UnresolvableTextContent("Reference (class=" + self.cls+") found but no phonetic match at specified offset ("+str(self.offset)+")! Expected '" + self.text() + "', got '" + ref.textcontent(self.cls).text()[self.offset:self.offset+len(self.data[0])] +"'")
else:
#finally, we made it!
return ref | def getreference(self, validate=True) | Return and validate the Phonetic Content's reference. Raises UnresolvableTextContent when invalid | 5.368237 | 4.505816 | 1.191402 |
depth = 0
e = self
while True:
if e.parent:
e = e.parent #pylint: disable=redefined-variable-type
else:
#no parent, breaking
return False
if isinstance(e,AbstractStructureElement) or isinstance(e,AbstractSubtokenAnnotation):
depth += 1
if depth == 2:
return e
return False | def finddefaultreference(self) | Find the default reference for text offsets:
The parent of the current textcontent's parent (counting only Structure Elements and Subtoken Annotation Elements)
Note: This returns not a TextContent element, but its parent. Whether the textcontent actually exists is checked later/elsewhere | 6.768433 | 4.726374 | 1.432056 |
if 'cls' not in kwargs:
kwargs['cls'] = 'current'
replace = super(PhonContent, Class).findreplaceables(parent, set, **kwargs)
replace = [ x for x in replace if x.cls == kwargs['cls']]
del kwargs['cls'] #always delete what we processed
return replace | def findreplaceables(Class, parent, set, **kwargs):#pylint: disable=bad-classmethod-argument
#some extra behaviour for text content elements, replace also based on the 'corrected' attribute | (Method for internal usage, see AbstractElement) | 6.413242 | 6.652963 | 0.963968 |
kwargs['offset'] = int(node.attrib['offset'])
if 'ref' in node.attrib:
kwargs['ref'] = node.attrib['ref']
return super(PhonContent,Class).parsexml(node,doc, **kwargs) | def parsexml(Class, node, doc, **kwargs):#pylint: disable=bad-classmethod-argument
if not kwargs: kwargs = {}
if 'offset' in node.attrib | (Method for internal usage, see AbstractElement) | 3.997076 | 3.26257 | 1.225131 |
for layer in self.select(MorphologyLayer):
for m in layer.select(Morpheme, set):
yield m | def morphemes(self,set=None) | Generator yielding all morphemes (in a particular set if specified). For retrieving one specific morpheme by index, use morpheme() instead | 11.18142 | 10.233871 | 1.092589 |
for layer in self.select(PhonologyLayer):
for p in layer.select(Phoneme, set):
yield p | def phonemes(self,set=None) | Generator yielding all phonemes (in a particular set if specified). For retrieving one specific morpheme by index, use morpheme() instead | 11.083857 | 11.890058 | 0.932195 |
for layer in self.select(MorphologyLayer):
for i, m in enumerate(layer.select(Morpheme, set)):
if index == i:
return m
raise NoSuchAnnotation | def morpheme(self,index, set=None) | Returns a specific morpheme, the n'th morpheme (given the particular set if specified). | 8.588072 | 8.075233 | 1.063508 |
for layer in self.select(PhonologyLayer):
for i, p in enumerate(layer.select(Phoneme, set)):
if index == i:
return p
raise NoSuchAnnotation | def phoneme(self,index, set=None) | Returns a specific phoneme, the n'th morpheme (given the particular set if specified). | 9.646661 | 9.092896 | 1.060901 |
if issubclass(type, AbstractAnnotationLayer):
layerclass = type
else:
layerclass = ANNOTATIONTYPE2LAYERCLASS[type.ANNOTATIONTYPE]
e = self
while True:
if not e.parent: break
e = e.parent
for layer in e.select(layerclass,set,False):
if type is layerclass:
for e2 in layer.select(AbstractSpanAnnotation,set,True, (True, Word, Morpheme)):
if not isinstance(e2, AbstractSpanRole) and self in e2.wrefs():
yield e2
else:
for e2 in layer.select(type,set,True, (True, Word, Morpheme)):
if not isinstance(e2, AbstractSpanRole) and self in e2.wrefs():
yield e2 | def findspans(self, type,set=None) | Yields span annotation elements of the specified type that include this word.
Arguments:
type: The annotation type, can be passed as using any of the :class:`AnnotationType` member, or by passing the relevant :class:`AbstractSpanAnnotation` or :class:`AbstractAnnotationLayer` class.
set (str or None): Constrain by set
Example::
for chunk in word.findspans(folia.Chunk):
print(" Chunk class=", chunk.cls, " words=")
for word2 in chunk.wrefs(): #print all words in the chunk (of which the word is a part)
print(word2, end="")
print()
Yields:
Matching span annotation instances (derived from :class:`AbstractSpanAnnotation`) | 4.399806 | 3.643013 | 1.207738 |
if self.doc and self.doc.deepvalidation and self.parent.set and self.parent.set[0] != '_':
try:
self.doc.setdefinitions[self.parent.set].testsubclass(self.parent.cls, self.subset, self.cls)
except KeyError as e:
if self.parent.cls and not self.doc.allowadhocsets:
raise DeepValidationError("Set definition " + self.parent.set + " for " + self.parent.XMLTAG + " not loaded (feature validation failed)!")
except DeepValidationError as e:
errormsg = str(e) + " (in set " + self.parent.set+" for " + self.parent.XMLTAG
if self.parent.id:
errormsg += " with ID " + self.parent.id
errormsg += ")"
raise DeepValidationError(errormsg) | def deepvalidation(self) | Perform deep validation of this element.
Raises:
:class:`DeepValidationError` | 5.78406 | 5.664185 | 1.021164 |
if not attribs: attribs = {}
E = ElementMaker(namespace="http://ilk.uvt.nl/folia",nsmap={None: "http://ilk.uvt.nl/folia", 'xml' : "http://www.w3.org/XML/1998/namespace"})
e = super(AbstractSpanAnnotation,self).xml(attribs, elements, True)
for child in self:
if isinstance(child, (Word, Morpheme, Phoneme)):
#Include REFERENCES to word items instead of word items themselves
attribs['{' + NSFOLIA + '}id'] = child.id
if child.PRINTABLE and child.hastext(self.textclass):
attribs['{' + NSFOLIA + '}t'] = child.text(self.textclass)
e.append( E.wref(**attribs) )
elif not (isinstance(child, Feature) and child.SUBSET): #Don't add pre-defined features, they are already added as attributes
e.append( child.xml() )
return e | def xml(self, attribs = None,elements = None, skipchildren = False) | See :meth:`AbstractElement.xml` | 5.275892 | 5.09641 | 1.035217 |
#Accept Word instances instead of WordReference, references will be automagically used upon serialisation
if isinstance(child, (Word, Morpheme, Phoneme)) and WordReference in self.ACCEPTED_DATA:
#We don't really append but do an insertion so all references are in proper order
insertionpoint = len(self.data)
for i, sibling in enumerate(self.data):
if isinstance(sibling, (Word, Morpheme, Phoneme)):
try:
if not sibling.precedes(child):
insertionpoint = i
except: #happens if we can't determine common ancestors
pass
self.data.insert(insertionpoint, child)
return child
elif isinstance(child, AbstractSpanAnnotation): #(covers span roles just as well)
insertionpoint = len(self.data)
try:
firstword = child.wrefs(0)
except IndexError:
#we have no basis to determine an insertionpoint for this child, just append it then
return super(AbstractSpanAnnotation,self).append(child, *args, **kwargs)
insertionpoint = len(self.data)
for i, sibling in enumerate(self.data):
if isinstance(sibling, (Word, Morpheme, Phoneme)):
try:
if not sibling.precedes(firstword):
insertionpoint = i
except: #happens if we can't determine common ancestors
pass
return super(AbstractSpanAnnotation,self).insert(insertionpoint, child, *args, **kwargs)
else:
return super(AbstractSpanAnnotation,self).append(child, *args, **kwargs) | def append(self, child, *args, **kwargs) | See :meth:`AbstractElement.append` | 4.537379 | 4.513813 | 1.005221 |
self.data = []
for child in args:
self.append(child) | def setspan(self, *args) | Sets the span of the span element anew, erases all data inside.
Arguments:
*args: Instances of :class:`Word`, :class:`Morpheme` or :class:`Phoneme` | 9.735983 | 8.566833 | 1.136474 |
return self.count(Class,set,True,default_ignore_annotations) | def hasannotation(self,Class,set=None) | Returns an integer indicating whether such as annotation exists, and if so, how many. See ``annotations()`` for a description of the parameters. | 29.672958 | 26.819527 | 1.106394 |
l = list(self.select(type,set,True,default_ignore_annotations))
if len(l) >= 1:
return l[0]
else:
raise NoSuchAnnotation() | def annotation(self, type, set=None) | Will return a **single** annotation (even if there are multiple). Raises a ``NoSuchAnnotation`` exception if none was found | 7.868321 | 6.085196 | 1.293027 |
for c in self:
if isinstance(c,Word) or isinstance(c,Morpheme) or isinstance(c, Phoneme):
targets.append(c)
elif isinstance(c,WordReference):
try:
targets.append(self.doc[c.id]) #try to resolve
except KeyError:
targets.append(c) #add unresolved
elif isinstance(c, AbstractSpanAnnotation) and recurse:
#recursion
c._helper_wrefs(targets) #pylint: disable=protected-access
elif isinstance(c, Correction) and c.auth: #recurse into corrections
for e in c:
if isinstance(e, AbstractCorrectionChild) and e.auth:
for e2 in e:
if isinstance(e2, AbstractSpanAnnotation):
#recursion
e2._helper_wrefs(targets) | def _helper_wrefs(self, targets, recurse=True) | Internal helper function | 4.463864 | 4.342996 | 1.027831 |
targets =[]
self._helper_wrefs(targets, recurse)
if index is None:
return targets
else:
return targets[index] | def wrefs(self, index = None, recurse=True) | Returns a list of word references, these can be Words but also Morphemes or Phonemes.
Arguments:
index (int or None): If set to an integer, will retrieve and return the n'th element (starting at 0) instead of returning the list of all | 5.743971 | 11.124097 | 0.516354 |
if not norecurse: norecurse = (Word, Morpheme, Phoneme)
if self.id:
self.doc.index[self.id] = self
for e in self.data:
if all([not isinstance(e, C) for C in norecurse]):
try:
e.addtoindex(norecurse)
except AttributeError:
pass | def addtoindex(self,norecurse=None) | Makes sure this element (and all subelements), are properly added to the index | 4.804466 | 4.211872 | 1.140696 |
if idsuffix is True: idsuffix = ".copy." + "%08x" % random.getrandbits(32) #random 32-bit hash for each copy, same one will be reused for all children
for c in self:
if isinstance(c, Word):
yield WordReference(newdoc, id=c.id)
else:
yield c.copy(newdoc,idsuffix) | def copychildren(self, newdoc=None, idsuffix="") | Generator creating a deep copy of the children of this element. If idsuffix is a string, if set to True, a random idsuffix will be generated including a random 32-bit hash | 6.518539 | 4.889394 | 1.3332 |
if self.set is False or self.set is None:
if len(self.data) == 0: #just skip if there are no children
return None
else:
raise ValueError("No set specified or derivable for annotation layer " + self.__class__.__name__)
return super(AbstractAnnotationLayer, self).xml(attribs, elements, skipchildren) | def xml(self, attribs = None,elements = None, skipchildren = False) | See :meth:`AbstractElement.xml` | 7.021594 | 6.40728 | 1.095877 |
#if no set is associated with the layer yet, we learn it from span annotation elements that are added
if self.set is False or self.set is None:
if inspect.isclass(child):
if issubclass(child,AbstractSpanAnnotation):
if 'set' in kwargs:
self.set = kwargs['set']
elif isinstance(child, AbstractSpanAnnotation):
if child.set:
self.set = child.set
elif isinstance(child, Correction):
#descend into corrections to find the proper set for this layer (derived from span annotation elements)
for e in itertools.chain( child.new(), child.original(), child.suggestions() ):
if isinstance(e, AbstractSpanAnnotation) and e.set:
self.set = e.set
break
return super(AbstractAnnotationLayer, self).append(child, *args, **kwargs) | def append(self, child, *args, **kwargs) | See :meth:`AbstractElement.append` | 5.417663 | 5.190551 | 1.043755 |
for e in self.select(AlternativeLayers,None, True, ['Original','Suggestion']): #pylint: disable=too-many-nested-blocks
if Class is None:
yield e
elif len(e) >= 1: #child elements?
for e2 in e:
try:
if isinstance(e2, Class):
try:
if set is None or e2.set == set:
yield e #not e2
break #yield an alternative only once (in case there are multiple matches)
except AttributeError:
continue
except AttributeError:
continue | def alternatives(self, Class=None, set=None) | Generator over alternatives, either all or only of a specific annotation type, and possibly restrained also by set.
Arguments:
* ``Class`` - The Class you want to retrieve (e.g. PosAnnotation). Or set to None to select all alternatives regardless of what type they are.
* ``set`` - The set you want to retrieve (defaults to None, which selects irregardless of set)
Returns:
Generator over Alternative elements | 7.841193 | 7.091237 | 1.105758 |
for span in self.select(AbstractSpanAnnotation,None,True):
if tuple(span.wrefs()) == words:
return span
raise NoSuchAnnotation | def findspan(self, *words) | Returns the span element which spans over the specified words or morphemes.
See also:
:meth:`Word.findspans` | 18.486383 | 24.539494 | 0.753332 |
E = ElementMaker(namespace="http://relaxng.org/ns/structure/1.0",nsmap={None:'http://relaxng.org/ns/structure/1.0' , 'folia': "http://ilk.uvt.nl/folia", 'xml' : "http://www.w3.org/XML/1998/namespace",'a':"http://relaxng.org/ns/annotation/0.9" })
if not extraattribs:
extraattribs = []
extraattribs.append(E.optional(E.attribute(E.text(), name='set')) )
return AbstractElement.relaxng(includechildren, extraattribs, extraelements, cls) | def relaxng(cls, includechildren=True,extraattribs = None, extraelements=None, origclass = None) | Returns a RelaxNG definition for this element (as an XML element (lxml.etree) rather than a string) | 3.591914 | 3.581299 | 1.002964 |
for e in self.select(New,None,False, False):
if not allowempty and len(e) == 0: continue
return True
return False | def hasnew(self,allowempty=False) | Does the correction define new corrected annotations? | 7.420764 | 7.780921 | 0.953713 |
for e in self.select(Original,None,False, False):
if not allowempty and len(e) == 0: continue
return True
return False | def hasoriginal(self,allowempty=False) | Does the correction record the old annotations prior to correction? | 6.85419 | 7.117364 | 0.963024 |
for e in self.select(Current,None,False, False):
if not allowempty and len(e) == 0: continue
return True
return False | def hascurrent(self, allowempty=False) | Does the correction record the current authoritative annotation (needed only in a structural context when suggestions are proposed) | 6.840613 | 7.672917 | 0.891527 |
for e in self.select(Suggestion,None,False, False):
if not allowempty and len(e) == 0: continue
return True
return False | def hassuggestions(self,allowempty=False) | Does the correction propose suggestions for correction? | 8.041162 | 8.082825 | 0.994845 |
if cls == 'original': correctionhandling = CorrectionHandling.ORIGINAL #backward compatibility
if correctionhandling in (CorrectionHandling.CURRENT, CorrectionHandling.EITHER):
for e in self:
if isinstance(e, New) or isinstance(e, Current):
return e.textcontent(cls,correctionhandling)
if correctionhandling in (CorrectionHandling.ORIGINAL, CorrectionHandling.EITHER):
for e in self:
if isinstance(e, Original):
return e.textcontent(cls,correctionhandling)
raise NoSuchText | def textcontent(self, cls='current', correctionhandling=CorrectionHandling.CURRENT) | See :meth:`AbstractElement.textcontent` | 2.99225 | 2.939816 | 1.017836 |
if cls == 'original': correctionhandling = CorrectionHandling.ORIGINAL #backward compatibility
if correctionhandling in (CorrectionHandling.CURRENT, CorrectionHandling.EITHER):
for e in self:
if isinstance(e, New) or isinstance(e, Current):
return e.phoncontent(cls, correctionhandling)
if correctionhandling in (CorrectionHandling.ORIGINAL, CorrectionHandling.EITHER):
for e in self:
if isinstance(e, Original):
return e.phoncontent(cls, correctionhandling)
raise NoSuchPhon | def phoncontent(self, cls='current', correctionhandling=CorrectionHandling.CURRENT) | See :meth:`AbstractElement.phoncontent` | 2.912434 | 2.777817 | 1.048462 |
if cls == 'original': correctionhandling = CorrectionHandling.ORIGINAL #backward compatibility
if correctionhandling in (CorrectionHandling.CURRENT, CorrectionHandling.EITHER):
for e in self:
if isinstance(e, New) or isinstance(e, Current):
return e.hastext(cls,strict, correctionhandling)
if correctionhandling in (CorrectionHandling.ORIGINAL, CorrectionHandling.EITHER):
for e in self:
if isinstance(e, Original):
return e.hastext(cls,strict, correctionhandling)
return False | def hastext(self, cls='current',strict=True, correctionhandling=CorrectionHandling.CURRENT) | See :meth:`AbstractElement.hastext` | 2.714889 | 2.61487 | 1.03825 |
if cls == 'original': correctionhandling = CorrectionHandling.ORIGINAL #backward compatibility
if correctionhandling in (CorrectionHandling.CURRENT, CorrectionHandling.EITHER):
for e in self:
if isinstance(e, New) or isinstance(e, Current):
s = previousdelimiter + e.text(cls, retaintokenisation,"", strict, correctionhandling)
if normalize_spaces:
return norm_spaces(s)
else:
return s
if correctionhandling in (CorrectionHandling.ORIGINAL, CorrectionHandling.EITHER):
for e in self:
if isinstance(e, Original):
s = previousdelimiter + e.text(cls, retaintokenisation,"", strict, correctionhandling)
if normalize_spaces:
return norm_spaces(s)
else:
return s
raise NoSuchText | def text(self, cls = 'current', retaintokenisation=False, previousdelimiter="",strict=False, correctionhandling=CorrectionHandling.CURRENT, normalize_spaces=False) | See :meth:`AbstractElement.text` | 2.726399 | 2.659499 | 1.025155 |
if cls == 'original': correctionhandling = CorrectionHandling.ORIGINAL #backward compatibility
if correctionhandling in (CorrectionHandling.CURRENT, CorrectionHandling.EITHER):
for e in self:
if isinstance(e, New) or isinstance(e, Current):
return previousdelimiter + e.phon(cls, "", strict, correctionhandling)
if correctionhandling in (CorrectionHandling.ORIGINAL, CorrectionHandling.EITHER):
for e in self:
if isinstance(e, Original):
return previousdelimiter + e.phon(cls, "", correctionhandling)
raise NoSuchPhon | def phon(self, cls = 'current', previousdelimiter="",strict=False, correctionhandling=CorrectionHandling.CURRENT) | See :meth:`AbstractElement.phon` | 3.346342 | 3.185877 | 1.050368 |
for e in self:
if isinstance(e, New) or isinstance(e, Current):
return e.gettextdelimiter(retaintokenisation)
return "" | def gettextdelimiter(self, retaintokenisation=False) | See :meth:`AbstractElement.gettextdelimiter` | 5.56823 | 4.427351 | 1.257689 |
if index is None:
try:
return next(self.select(New,None,False))
except StopIteration:
raise NoSuchAnnotation
else:
for e in self.select(New,None,False):
return e[index]
raise NoSuchAnnotation | def new(self,index = None) | Get the new corrected annotation.
This returns only one annotation if multiple exist, use `index` to select another in the sequence.
Returns:
an annotation element (:class:`AbstractElement`)
Raises:
:class:`NoSuchAnnotation` | 5.627785 | 4.560728 | 1.233966 |
if index is None:
try:
return next(self.select(Original,None,False, False))
except StopIteration:
raise NoSuchAnnotation
else:
for e in self.select(Original,None,False, False):
return e[index]
raise NoSuchAnnotation | def original(self,index=None) | Get the old annotation prior to correction.
This returns only one annotation if multiple exist, use `index` to select another in the sequence.
Returns:
an annotation element (:class:`AbstractElement`)
Raises:
:class:`NoSuchAnnotation` | 5.23323 | 4.942699 | 1.05878 |
if index is None:
try:
return next(self.select(Current,None,False))
except StopIteration:
raise NoSuchAnnotation
else:
for e in self.select(Current,None,False):
return e[index]
raise NoSuchAnnotation | def current(self,index=None) | Get the current authoritative annotation (used with suggestions in a structural context)
This returns only one annotation if multiple exist, use `index` to select another in the sequence.
Returns:
an annotation element (:class:`AbstractElement`)
Raises:
:class:`NoSuchAnnotation` | 5.155474 | 4.562819 | 1.129888 |
if index is None:
return self.select(Suggestion,None,False, False)
else:
for i, e in enumerate(self.select(Suggestion,None,False, False)):
if index == i:
return e
raise IndexError | def suggestions(self,index=None) | Get suggestions for correction.
Yields:
:class:`Suggestion` element that encapsulate the suggested annotations (if index is ``None``, default)
Returns:
a :class:`Suggestion` element that encapsulate the suggested annotations (if index is set)
Raises:
:class:`IndexError` | 4.012935 | 5.396261 | 0.743651 |
if self.include:
return self.subdoc.data[0].select(Class,set,recursive, ignore, node) #pass it on to the text node of the subdoc
else:
return iter([]) | def select(self, Class, set=None, recursive=True, ignore=True, node=None) | See :meth:`AbstractElement.select` | 12.128428 | 10.877096 | 1.115043 |
E = ElementMaker(namespace=NSFOLIA,nsmap={None: NSFOLIA, 'xml' : "http://www.w3.org/XML/1998/namespace"})
if not attribs: attribs = {}
if not elements: elements = []
if self.id:
attribs['id'] = self.id
try:
w = self.doc[self.id]
attribs['t'] = w.text()
except KeyError:
pass
e = makeelement(E, '{' + NSFOLIA + '}' + self.XMLTAG, **attribs)
return e | def xml(self, attribs = None,elements = None, skipchildren = False) | Serialises the FoLiA element to XML, by returning an XML Element (in lxml.etree) for this element and all its children. For string output, consider the xmlstring() method instead. | 3.963631 | 3.505614 | 1.130653 |
l = self.count(type,set,True,default_ignore_annotations)
if len(l) >= 1:
return l[0]
else:
raise NoSuchAnnotation() | def annotation(self, type, set=None) | Will return a **single** annotation (even if there are multiple). Raises a ``NoSuchAnnotation`` exception if none was found | 9.0812 | 6.726157 | 1.350132 |
if issubclass(type, AbstractAnnotationLayer):
layerclass = type
else:
layerclass = ANNOTATIONTYPE2LAYERCLASS[type.ANNOTATIONTYPE]
e = self
while True:
if not e.parent: break
e = e.parent
for layer in e.select(layerclass,set,False):
for e2 in layer:
if isinstance(e2, AbstractSpanAnnotation):
if self in e2.wrefs():
yield e2 | def findspans(self, type,set=None) | Find span annotation of the specified type that include this word | 5.815892 | 5.41888 | 1.073265 |
for w in originalwords:
if not isinstance(w, Word):
raise Exception("Original word is not a Word instance: " + str(type(w)))
elif w.sentence() != self:
raise Exception("Original not found as member of sentence!")
for w in newwords:
if not isinstance(w, Word):
raise Exception("New word is not a Word instance: " + str(type(w)))
if 'suggest' in kwargs and kwargs['suggest']:
del kwargs['suggest']
return self.correct(suggestion=newwords,current=originalwords, **kwargs)
else:
return self.correct(original=originalwords, new=newwords, **kwargs) | def correctwords(self, originalwords, newwords, **kwargs) | Generic correction method for words. You most likely want to use the helper functions
:meth:`Sentence.splitword` , :meth:`Sentence.mergewords`, :meth:`deleteword`, :meth:`insertword` instead | 3.150814 | 3.340971 | 0.943083 |
if isstring(originalword):
originalword = self.doc[u(originalword)]
return self.correctwords([originalword], newwords, **kwargs) | def splitword(self, originalword, *newwords, **kwargs) | TODO: Write documentation | 7.82371 | 7.573789 | 1.032998 |
return self.correctwords(originalwords, [newword], **kwargs) | def mergewords(self, newword, *originalwords, **kwargs) | TODO: Write documentation | 9.721261 | 9.146777 | 1.062807 |
if isstring(word):
word = self.doc[u(word)]
return self.correctwords([word], [], **kwargs) | def deleteword(self, word, **kwargs) | TODO: Write documentation | 15.244138 | 14.577377 | 1.045739 |
if nextword:
if isstring(nextword):
nextword = self.doc[u(nextword)]
if not nextword in self or not isinstance(nextword, Word):
raise Exception("Next word not found or not instance of Word!")
if isinstance(newword, list) or isinstance(newword, tuple):
if not all([ isinstance(x, Word) for x in newword ]):
raise Exception("New word (iterable) constains non-Word instances!")
elif not isinstance(newword, Word):
raise Exception("New word no instance of Word!")
kwargs['insertindex'] = self.getindex(nextword)
else:
kwargs['insertindex'] = 0
kwargs['nooriginal'] = True
if isinstance(newword, list) or isinstance(newword, tuple):
return self.correctwords([], newword, **kwargs)
else:
return self.correctwords([], [newword], **kwargs) | def insertwordleft(self, newword, nextword, **kwargs) | Inserts a word **as a correction** before an existing word.
Reverse of :meth:`Sentence.insertword`. | 3.607819 | 3.508991 | 1.028164 |
if not self.variablesize():
raise Exception("Can only resize patterns with * wildcards")
nrofwildcards = 0
for x in self.sequence:
if x == '*':
nrofwildcards += 1
assert (len(distribution) == nrofwildcards)
wildcardnr = 0
newsequence = []
for x in self.sequence:
if x == '*':
newsequence += [True] * distribution[wildcardnr]
wildcardnr += 1
else:
newsequence.append(x)
d = { 'matchannotation':self.matchannotation, 'matchannotationset':self.matchannotationset, 'casesensitive':self.casesensitive }
yield Pattern(*newsequence, **d ) | def resolve(self,size, distribution) | Resolve a variable sized pattern to all patterns of a certain fixed size | 5.030635 | 4.761897 | 1.056435 |
#if LXE and self.mode != Mode.XPATH:
# #workaround for xml:id problem (disabled)
# #f = open(filename)
# #s = f.read().replace(' xml:id=', ' id=')
# #f.close()
# self.tree = ElementTree.parse(filename)
#else:
self.tree = xmltreefromfile(filename)
self.parsexml(self.tree.getroot())
if self.mode != Mode.XPATH:
#XML Tree is now obsolete (only needed when partially loaded for xpath queries)
self.tree = None | def load(self, filename) | Load a FoLiA XML file.
Argument:
filename (str): The file to load | 6.271705 | 6.556868 | 0.956509 |
l = []
for e in self.data:
l += e.items()
return l | def items(self) | Returns a depth-first flat list of all items in the document | 6.009556 | 5.584836 | 1.076049 |
for result in self.tree.xpath(query,namespaces={'f': 'http://ilk.uvt.nl/folia','folia': 'http://ilk.uvt.nl/folia' }):
yield self.parsexml(result) | def xpath(self, query) | Run Xpath expression and parse the resulting elements. Don't forget to use the FoLiA namesapace in your expressions, using folia: or the short form f: | 5.075056 | 3.539121 | 1.433988 |
if inspect.isclass(annotationtype): annotationtype = annotationtype.ANNOTATIONTYPE
if annotationtype in self.set_alias and set in self.set_alias[annotationtype]:
return self.set_alias[annotationtype][set]
elif fallback:
return set
else:
raise KeyError("No alias for set " + set) | def alias(self, annotationtype, set, fallback=False) | Return the alias for a set (if applicable, returns the unaltered set otherwise iff fallback is enabled) | 2.978816 | 2.538054 | 1.173661 |
if inspect.isclass(annotationtype): annotationtype = annotationtype.ANNOTATIONTYPE
return self.alias_set[annotationtype][alias] | def unalias(self, annotationtype, alias) | Return the set for an alias (if applicable, raises an exception otherwise) | 6.0963 | 4.455803 | 1.368171 |
if not filename:
filename = self.filename
if not filename:
raise Exception("No filename specified")
if filename[-4:].lower() == '.bz2':
f = bz2.BZ2File(filename,'wb')
f.write(self.xmlstring().encode('utf-8'))
f.close()
elif filename[-3:].lower() == '.gz':
f = gzip.GzipFile(filename,'wb') #pylint: disable=redefined-variable-type
f.write(self.xmlstring().encode('utf-8'))
f.close()
else:
f = io.open(filename,'w',encoding='utf-8')
f.write(self.xmlstring())
f.close() | def save(self, filename=None) | Save the document to file.
Arguments:
* filename (str): The filename to save to. If not set (``None``, default), saves to the same file as loaded from. | 1.896985 | 1.964585 | 0.965591 |
if text is Text:
text = Text(self, id=self.id + '.text.' + str(len(self.data)+1) )
elif text is Speech:
text = Speech(self, id=self.id + '.speech.' + str(len(self.data)+1) ) #pylint: disable=redefined-variable-type
else:
assert isinstance(text, Text) or isinstance(text, Speech)
self.data.append(text)
return text | def append(self,text) | Add a text (or speech) to the document:
Example 1::
doc.append(folia.Text)
Example 2::
doc.append( folia.Text(doc, id='example.text') )
Example 3::
doc.append(folia.Speech) | 3.023391 | 2.696072 | 1.121406 |
End of preview. Expand
in Data Studio
- Downloads last month
- 13