func_code_string stringlengths 52 1.94M | func_documentation_string stringlengths 1 47.2k |
|---|---|
def addidsuffix(self, idsuffix, recursive = True):
if self.id: self.id += idsuffix
if recursive:
for e in self:
try:
e.addidsuffix(idsuffix, recursive)
except Exception:
pass | 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` |
def setparents(self):
for c in self:
if isinstance(c, AbstractElement):
c.parent = self
c.setparents() | Correct all parent relations for elements within the scop. There is sually no need to call this directly, invoked implicitly by :meth:`copy` |
def setdoc(self,newdoc):
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) | Set a different document. Usually no need to call this directly, invoked implicitly by :meth:`copy` |
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:
return True
else:
... | 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``.
... |
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:
return True
else:
... | 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, ... |
def settext(self, text, cls='current'):
self.replace(TextContent, value=text, cls=cls) | 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. |
def setdocument(self, doc):
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... | Associate a document with this element.
Arguments:
doc (:class:`Document`): A document
Each element must be associated with a FoLiA document. |
def addable(Class, parent, set=None, raiseexceptions=True):
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,... | 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 tha... |
def postappend(self):
#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() | 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. |
def deepvalidation(self):
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:
rai... | Perform deep validation of this element.
Raises:
:class:`DeepValidationError` |
def findreplaceables(Class, parent, set=None,**kwargs):
return list(parent.select(Class,set,False)) | Internal method to find replaceable elements. Auxiliary function used by :meth:`AbstractElement.replace`. Can be overriden for more fine-grained control. |
def updatetext(self):
if self.TEXTCONTAINER:
s = ""
for child in self:
if isinstance(child, AbstractElement):
child.updatetext()
s += child.text()
elif isstring(child):
s += child
... | Recompute textual value based on the text content of the children. Only supported on elements that are a ``TEXTCONTAINER`` |
def replace(self, child, *args, **kwargs):
if 'set' in kwargs:
set = kwargs['set']
del kwargs['set']
else:
try:
set = child.set
except AttributeError:
set = None
if inspect.isclass(child):
Class ... | 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... |
def ancestors(self, Class=None):
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... | 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 de... |
def ancestor(self, *Classes):
for e in self.ancestors(tuple(Classes)):
return e
raise NoSuchAnnotation | 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) |
def xml(self, attribs = None,elements = None, skipchildren = False):
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['{http://www... | Serialises the FoLiA element and all its contents to XML.
Arguments are mostly for internal use.
Returns:
an lxml.etree.Element
See also:
:meth:`AbstractElement.xmlstring` - for direct string output |
def json(self, attribs=None, recurse=True, ignorelist=False):
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
i... | 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 |
def xmlstring(self, pretty_print=False):
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:
... | Serialises this FoLiA element and all its contents to XML.
Returns:
str: a string with XML representation for this element and all its children |
def select(self, Class, set=None, recursive=True, ignore=True, node=None): #pylint: disable=bad-classmethod-argument,redefined-builtin
#if ignorelist is True:
# ignorelist = default_ignore
if not node:
node = self
for e in self.data: #pylint: disable=too-many-nes... | 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 ... |
def count(self, Class, set=None, recursive=True, ignore=True, node=None):
return sum(1 for i in self.select(Class,set,recursive,ignore,node) ) | Like :meth:`AbstractElement.select`, but instead of returning the elements, it merely counts them.
Returns:
int |
def items(self, founditems=[]): #pylint: disable=dangerous-default-value
l = []
for e in self.data:
if e not in founditems: #prevent going in recursive loops
l.append(e)
if isinstance(e, AbstractElement):
l += e.items(l)
r... | Returns a depth-first flat list of *all* items below this element (not limited to AbstractElement) |
def getmetadata(self, key=None):
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... | Get the metadata that applies to this element, automatically inherited from parent elements |
def getindex(self, child, recursive=True, ignore=True):
#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 ign... | Get the index at which an element occurs, recursive by default!
Returns:
int |
def precedes(self, other):
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):
... | Returns a boolean indicating whether this element precedes the other element |
def depthfirstsearch(self, function):
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 | Generic depth first search algorithm using a callback function, continues as long as the callback function returns None |
def next(self, Class=True, scope=True, reverse=False):
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
descendinde... | 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 `'AbstractElemen... |
def previous(self, Class=True, scope=True):
return self.next(Class,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 `'AbstractEl... |
def leftcontext(self, size, placeholder=None, scope=None):
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:
... | 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 |
def rightcontext(self, size, placeholder=None, scope=None):
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:
w... | 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 |
def context(self, size, placeholder=None, scope=None):
return self.leftcontext(size, placeholder,scope) + [self] + self.rightcontext(size, placeholder,scope) | Returns this word in context, {size} words to the left, the current word, and {size} words to the right |
def relaxng(cls, includechildren=True,extraattribs = None, extraelements=None, origclass = None):
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':"... | Returns a RelaxNG definition for this element (as an XML element (lxml.etree) rather than a string) |
def parsexml(Class, node, doc, **kwargs): #pylint: disable=bad-classmethod-argument
assert issubclass(Class, AbstractElement)
if doc.preparsexmlcallback:
result = doc.preparsexmlcallback(node)
if not result:
return None
if isinstance(result, A... | Internal class method used for turning an XML element into an instance of the Class.
Args:
* ``node`` - XML Element
* ``doc`` - Document
Returns:
An instance of the current Class. |
def remove(self, child):
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.... | Removes the child element |
def incorrection(self):
e = self.parent
while e:
if isinstance(e, Correction):
return e
if isinstance(e, AbstractStructureElement):
break
e = e.parent
return None | Is this element part of a correction? If it is, it returns the Correction element (evaluating to True), otherwise it returns None |
def correct(self, **kwargs):
if 'insertindex_offset' in kwargs:
del kwargs['insertindex_offset'] #dealt with in an earlier stage
if 'confidence' in kwargs and kwargs['confidence'] is None:
del kwargs['confidence']
if 'reuse' in kwargs:
#reuse an exist... | Apply a correction (TODO: documentation to be written still) |
def annotations(self,Class,set=None):
found = False
for e in self.select(Class,set,True,default_ignore_annotations):
found = True
yield e
if not found:
raise NoSuchAnnotation() | 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 ... |
def hasannotation(self,Class,set=None):
return sum( 1 for _ in self.select(Class,set,True,default_ignore_annotations)) | Returns an integer indicating whether such as annotation exists, and if so, how many.
See :meth:`AllowTokenAnnotation.annotations`` for a description of the parameters. |
def annotation(self, type, set=None):
for e in self.select(type,set,True,default_ignore_annotations):
return e
raise NoSuchAnnotation() | 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 w... |
def append(self, child, *args, **kwargs):
e = super(AbstractStructureElement,self).append(child, *args, **kwargs)
self._setmaxid(e)
return e | See ``AbstractElement.append()`` |
def words(self, index = None):
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,Tr... | 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 |
def paragraphs(self, index = None):
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.selec... | 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 |
def sentences(self, index = None):
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(S... | 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 |
def layers(self, annotationtype=None,set=None):
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 ] | Returns a list of annotation layers found *directly* under this element, does not include alternative layers |
def hasannotationlayer(self, annotationtype=None,set=None):
l = self.layers(annotationtype, set)
return (len(l) > 0) | Does the specified annotation layer exist? |
def xml(self, attribs = None,elements = None, skipchildren = False):
if not attribs: attribs = {}
if self.idref:
attribs['id'] = self.idref
return super(AbstractTextMarkup,self).xml(attribs,elements, skipchildren) | See :meth:`AbstractElement.xml` |
def json(self,attribs =None, recurse=True, ignorelist=False):
if not attribs: attribs = {}
if self.idref:
attribs['id'] = self.idref
return super(AbstractTextMarkup,self).json(attribs,recurse, ignorelist) | See :meth:`AbstractElement.json` |
def text(self, normalize_spaces=False):
return super(TextContent,self).text(normalize_spaces=normalize_spaces) | Obtain the text (unicode instance) |
def getreference(self, validate=True):
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 textcont... | Returns and validates the Text Content's reference. Raises UnresolvableTextContent when invalid |
def xml(self, attribs = None,elements = None, skipchildren = False):
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 != 'cu... | See :meth:`AbstractElement.xml` |
def getreference(self, validate=True):
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... | Return and validate the Phonetic Content's reference. Raises UnresolvableTextContent when invalid |
def finddefaultreference(self):
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,AbstractStructure... | 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 |
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:
if 'cls' not in kwargs:
kwargs['cls'] = 'current'
replace = super(PhonContent, Class... | (Method for internal usage, see AbstractElement) |
def parsexml(Class, node, doc, **kwargs):#pylint: disable=bad-classmethod-argument
if not kwargs: kwargs = {}
if 'offset' in node.attrib:
kwargs['offset'] = int(node.attrib['offset'])
if 'ref' in node.attrib:
kwargs['ref'] = node.attrib['ref']
return supe... | (Method for internal usage, see AbstractElement) |
def morphemes(self,set=None):
for layer in self.select(MorphologyLayer):
for m in layer.select(Morpheme, set):
yield m | Generator yielding all morphemes (in a particular set if specified). For retrieving one specific morpheme by index, use morpheme() instead |
def phonemes(self,set=None):
for layer in self.select(PhonologyLayer):
for p in layer.select(Phoneme, set):
yield p | Generator yielding all phonemes (in a particular set if specified). For retrieving one specific morpheme by index, use morpheme() instead |
def morpheme(self,index, set=None):
for layer in self.select(MorphologyLayer):
for i, m in enumerate(layer.select(Morpheme, set)):
if index == i:
return m
raise NoSuchAnnotation | Returns a specific morpheme, the n'th morpheme (given the particular set if specified). |
def phoneme(self,index, set=None):
for layer in self.select(PhonologyLayer):
for i, p in enumerate(layer.select(Phoneme, set)):
if index == i:
return p
raise NoSuchAnnotation | Returns a specific phoneme, the n'th morpheme (given the particular set if specified). |
def findspans(self, type,set=None):
if issubclass(type, AbstractAnnotationLayer):
layerclass = type
else:
layerclass = ANNOTATIONTYPE2LAYERCLASS[type.ANNOTATIONTYPE]
e = self
while True:
if not e.parent: break
e = e.parent
... | 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... |
def deepvalidation(self):
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.p... | Perform deep validation of this element.
Raises:
:class:`DeepValidationError` |
def xml(self, attribs = None,elements = None, skipchildren = False):
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(attr... | See :meth:`AbstractElement.xml` |
def append(self, child, *args, **kwargs):
#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... | See :meth:`AbstractElement.append` |
def setspan(self, *args):
self.data = []
for child in args:
self.append(child) | Sets the span of the span element anew, erases all data inside.
Arguments:
*args: Instances of :class:`Word`, :class:`Morpheme` or :class:`Phoneme` |
def hasannotation(self,Class,set=None):
return self.count(Class,set,True,default_ignore_annotations) | Returns an integer indicating whether such as annotation exists, and if so, how many. See ``annotations()`` for a description of the parameters. |
def annotation(self, type, set=None):
l = list(self.select(type,set,True,default_ignore_annotations))
if len(l) >= 1:
return l[0]
else:
raise NoSuchAnnotation() | Will return a **single** annotation (even if there are multiple). Raises a ``NoSuchAnnotation`` exception if none was found |
def _helper_wrefs(self, targets, recurse=True):
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]) #... | Internal helper function |
def wrefs(self, index = None, recurse=True):
targets =[]
self._helper_wrefs(targets, recurse)
if index is None:
return targets
else:
return targets[index] | 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 |
def addtoindex(self,norecurse=None):
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(no... | Makes sure this element (and all subelements), are properly added to the index |
def copychildren(self, newdoc=None, idsuffix=""):
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,... | 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 |
def xml(self, attribs = None,elements = None, skipchildren = False):
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 annota... | See :meth:`AbstractElement.xml` |
def append(self, child, *args, **kwargs):
#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):
... | See :meth:`AbstractElement.append` |
def alternatives(self, Class=None, set=None):
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:
... | 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... |
def findspan(self, *words):
for span in self.select(AbstractSpanAnnotation,None,True):
if tuple(span.wrefs()) == words:
return span
raise NoSuchAnnotation | Returns the span element which spans over the specified words or morphemes.
See also:
:meth:`Word.findspans` |
def relaxng(cls, includechildren=True,extraattribs = None, extraelements=None, origclass = None):
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':"... | Returns a RelaxNG definition for this element (as an XML element (lxml.etree) rather than a string) |
def hasnew(self,allowempty=False):
for e in self.select(New,None,False, False):
if not allowempty and len(e) == 0: continue
return True
return False | Does the correction define new corrected annotations? |
def hasoriginal(self,allowempty=False):
for e in self.select(Original,None,False, False):
if not allowempty and len(e) == 0: continue
return True
return False | Does the correction record the old annotations prior to correction? |
def hascurrent(self, allowempty=False):
for e in self.select(Current,None,False, False):
if not allowempty and len(e) == 0: continue
return True
return False | Does the correction record the current authoritative annotation (needed only in a structural context when suggestions are proposed) |
def hassuggestions(self,allowempty=False):
for e in self.select(Suggestion,None,False, False):
if not allowempty and len(e) == 0: continue
return True
return False | Does the correction propose suggestions for correction? |
def textcontent(self, cls='current', correctionhandling=CorrectionHandling.CURRENT):
if cls == 'original': correctionhandling = CorrectionHandling.ORIGINAL #backward compatibility
if correctionhandling in (CorrectionHandling.CURRENT, CorrectionHandling.EITHER):
for e in self:
... | See :meth:`AbstractElement.textcontent` |
def phoncontent(self, cls='current', correctionhandling=CorrectionHandling.CURRENT):
if cls == 'original': correctionhandling = CorrectionHandling.ORIGINAL #backward compatibility
if correctionhandling in (CorrectionHandling.CURRENT, CorrectionHandling.EITHER):
for e in self:
... | See :meth:`AbstractElement.phoncontent` |
def hastext(self, cls='current',strict=True, correctionhandling=CorrectionHandling.CURRENT):
if cls == 'original': correctionhandling = CorrectionHandling.ORIGINAL #backward compatibility
if correctionhandling in (CorrectionHandling.CURRENT, CorrectionHandling.EITHER):
for e in self... | See :meth:`AbstractElement.hastext` |
def text(self, cls = 'current', retaintokenisation=False, previousdelimiter="",strict=False, correctionhandling=CorrectionHandling.CURRENT, normalize_spaces=False):
if cls == 'original': correctionhandling = CorrectionHandling.ORIGINAL #backward compatibility
if correctionhandling in (Correctio... | See :meth:`AbstractElement.text` |
def phon(self, cls = 'current', previousdelimiter="",strict=False, correctionhandling=CorrectionHandling.CURRENT):
if cls == 'original': correctionhandling = CorrectionHandling.ORIGINAL #backward compatibility
if correctionhandling in (CorrectionHandling.CURRENT, CorrectionHandling.EITHER):
... | See :meth:`AbstractElement.phon` |
def gettextdelimiter(self, retaintokenisation=False):
for e in self:
if isinstance(e, New) or isinstance(e, Current):
return e.gettextdelimiter(retaintokenisation)
return "" | See :meth:`AbstractElement.gettextdelimiter` |
def new(self,index = None):
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]
ra... | 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` |
def original(self,index=None):
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):
ret... | 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` |
def current(self,index=None):
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]
... | 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:`NoSuchA... |
def suggestions(self,index=None):
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 | 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... |
def select(self, Class, set=None, recursive=True, ignore=True, node=None):
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([]) | See :meth:`AbstractElement.select` |
def xml(self, attribs = None,elements = None, skipchildren = False):
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... | 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. |
def annotation(self, type, set=None):
l = self.count(type,set,True,default_ignore_annotations)
if len(l) >= 1:
return l[0]
else:
raise NoSuchAnnotation() | Will return a **single** annotation (even if there are multiple). Raises a ``NoSuchAnnotation`` exception if none was found |
def findspans(self, type,set=None):
if issubclass(type, AbstractAnnotationLayer):
layerclass = type
else:
layerclass = ANNOTATIONTYPE2LAYERCLASS[type.ANNOTATIONTYPE]
e = self
while True:
if not e.parent: break
e = e.parent
... | Find span annotation of the specified type that include this word |
def correctwords(self, originalwords, newwords, **kwargs):
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 ... | 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 |
def splitword(self, originalword, *newwords, **kwargs):
if isstring(originalword):
originalword = self.doc[u(originalword)]
return self.correctwords([originalword], newwords, **kwargs) | TODO: Write documentation |
def mergewords(self, newword, *originalwords, **kwargs):
return self.correctwords(originalwords, [newword], **kwargs) | TODO: Write documentation |
def deleteword(self, word, **kwargs):
if isstring(word):
word = self.doc[u(word)]
return self.correctwords([word], [], **kwargs) | TODO: Write documentation |
def insertwordleft(self, newword, nextword, **kwargs):
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!")
... | Inserts a word **as a correction** before an existing word.
Reverse of :meth:`Sentence.insertword`. |
def resolve(self,size, distribution):
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) == nrofwildc... | Resolve a variable sized pattern to all patterns of a certain fixed size |
def load(self, filename):
#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:
... | Load a FoLiA XML file.
Argument:
filename (str): The file to load |
def items(self):
l = []
for e in self.data:
l += e.items()
return l | Returns a depth-first flat list of all items in the document |
def xpath(self, query):
for result in self.tree.xpath(query,namespaces={'f': 'http://ilk.uvt.nl/folia','folia': 'http://ilk.uvt.nl/folia' }):
yield self.parsexml(result) | 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: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.