repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_code_tokens
sequencelengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
sequencelengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|---|---|---|
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.addidsuffix | 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`"""
if self.id: self.id += idsuffix
if recursive:
for e in self:
try:
e.addidsuffix(idsuffix, recursive)
except Exception:
pass | python | 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`"""
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",
")",
":",
"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` | [
"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"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1263-L1271 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.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`"""
for c in self:
if isinstance(c, AbstractElement):
c.parent = self
c.setparents() | python | 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`"""
for c in self:
if isinstance(c, AbstractElement):
c.parent = self
c.setparents() | [
"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` | [
"Correct",
"all",
"parent",
"relations",
"for",
"elements",
"within",
"the",
"scop",
".",
"There",
"is",
"sually",
"no",
"need",
"to",
"call",
"this",
"directly",
"invoked",
"implicitly",
"by",
":",
"meth",
":",
"copy"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1273-L1278 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.setdoc | def setdoc(self,newdoc):
"""Set a different document. Usually no need to call this directly, invoked implicitly by :meth:`copy`"""
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) | python | def setdoc(self,newdoc):
"""Set a different document. Usually no need to call this directly, invoked implicitly by :meth:`copy`"""
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",
")",
":",
"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` | [
"Set",
"a",
"different",
"document",
".",
"Usually",
"no",
"need",
"to",
"call",
"this",
"directly",
"invoked",
"implicitly",
"by",
":",
"meth",
":",
"copy"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1280-L1287 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.hastext | def hastext(self,cls='current',strict=True, correctionhandling=CorrectionHandling.CURRENT): #pylint: disable=too-many-return-statements
"""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
"""
if not self.PRINTABLE: #only printable elements can hold text
return False
elif self.TEXTCONTAINER:
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 | python | def hastext(self,cls='current',strict=True, correctionhandling=CorrectionHandling.CURRENT): #pylint: disable=too-many-return-statements
"""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
"""
if not self.PRINTABLE: #only printable elements can hold text
return False
elif self.TEXTCONTAINER:
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",
":",
"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"
] | 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 | [
"Does",
"this",
"element",
"have",
"text",
"(",
"of",
"the",
"specified",
"class",
")"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1289-L1321 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.hasphon | def hasphon(self,cls='current',strict=True,correctionhandling=CorrectionHandling.CURRENT): #pylint: disable=too-many-return-statements
"""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
"""
if not self.SPEAKABLE: #only printable elements can hold text
return False
elif self.PHONCONTAINER:
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 | python | def hasphon(self,cls='current',strict=True,correctionhandling=CorrectionHandling.CURRENT): #pylint: disable=too-many-return-statements
"""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
"""
if not self.SPEAKABLE: #only printable elements can hold text
return False
elif self.PHONCONTAINER:
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",
":",
"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"
] | 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 | [
"Does",
"this",
"element",
"have",
"phonetic",
"content",
"(",
"of",
"the",
"specified",
"class",
")"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1323-L1355 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.settext | 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.
"""
self.replace(TextContent, value=text, cls=cls) | python | 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.
"""
self.replace(TextContent, value=text, cls=cls) | [
"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. | [
"Set",
"the",
"text",
"for",
"this",
"element",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1357-L1364 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.setdocument | 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.
"""
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) | python | 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.
"""
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",
")",
":",
"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",
")"
] | Associate a document with this element.
Arguments:
doc (:class:`Document`): A document
Each element must be associated with a FoLiA document. | [
"Associate",
"a",
"document",
"with",
"this",
"element",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1366-L1385 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.addable | 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
"""
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 | python | 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
"""
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",
")",
":",
"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"
] | 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 | [
"Tests",
"whether",
"a",
"new",
"element",
"of",
"this",
"class",
"can",
"be",
"added",
"to",
"the",
"parent",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1406-L1455 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.postappend | 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.
"""
#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() | python | 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.
"""
#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",
")",
":",
"#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. | [
"This",
"method",
"will",
"be",
"called",
"after",
"an",
"element",
"is",
"added",
"to",
"another",
"and",
"does",
"some",
"checks",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1458-L1471 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.deepvalidation | def deepvalidation(self):
"""Perform deep validation of this element.
Raises:
:class:`DeepValidationError`
"""
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) | python | def deepvalidation(self):
"""Perform deep validation of this element.
Raises:
:class:`DeepValidationError`
"""
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",
")",
":",
"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",
")"
] | Perform deep validation of this element.
Raises:
:class:`DeepValidationError` | [
"Perform",
"deep",
"validation",
"of",
"this",
"element",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1486-L1503 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.findreplaceables | 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."""
return list(parent.select(Class,set,False)) | python | 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."""
return list(parent.select(Class,set,False)) | [
"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. | [
"Internal",
"method",
"to",
"find",
"replaceable",
"elements",
".",
"Auxiliary",
"function",
"used",
"by",
":",
"meth",
":",
"AbstractElement",
".",
"replace",
".",
"Can",
"be",
"overriden",
"for",
"more",
"fine",
"-",
"grained",
"control",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1766-L1768 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.updatetext | def updatetext(self):
"""Recompute textual value based on the text content of the children. Only supported on elements that are a ``TEXTCONTAINER``"""
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] | python | def updatetext(self):
"""Recompute textual value based on the text content of the children. Only supported on elements that are a ``TEXTCONTAINER``"""
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",
")",
":",
"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",
"]"
] | Recompute textual value based on the text content of the children. Only supported on elements that are a ``TEXTCONTAINER`` | [
"Recompute",
"textual",
"value",
"based",
"on",
"the",
"text",
"content",
"of",
"the",
"children",
".",
"Only",
"supported",
"on",
"elements",
"that",
"are",
"a",
"TEXTCONTAINER"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1772-L1782 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.replace | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | 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. | [
"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",
"()"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1784-L1838 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.ancestors | 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`)
"""
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 | python | 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`)
"""
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",
")",
":",
"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"
] | 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`) | [
"Generator",
"yielding",
"all",
"ancestors",
"of",
"this",
"element",
"effectively",
"back",
"-",
"tracing",
"its",
"path",
"to",
"the",
"root",
"element",
".",
"A",
"tuple",
"of",
"multiple",
"classes",
"may",
"be",
"specified",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1840-L1860 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.ancestor | 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)
"""
for e in self.ancestors(tuple(Classes)):
return e
raise NoSuchAnnotation | python | 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)
"""
for e in self.ancestors(tuple(Classes)):
return e
raise NoSuchAnnotation | [
"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) | [
"Find",
"the",
"most",
"immediate",
"ancestor",
"of",
"the",
"specified",
"type",
"multiple",
"classes",
"may",
"be",
"specified",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1862-L1874 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.xml | def xml(self, attribs = None,elements = None, skipchildren = False):
"""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
"""
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.w3.org/XML/1998/namespace}id'] = self.id
#Some attributes only need to be added if they are not the same as what's already set in the declaration
if not isinstance(self, AbstractAnnotationLayer):
if '{' + NSFOLIA + '}set' not in attribs: #do not override if overloaded function already set it
try:
if self.set:
if not self.ANNOTATIONTYPE in self.doc.annotationdefaults or len(self.doc.annotationdefaults[self.ANNOTATIONTYPE]) != 1 or list(self.doc.annotationdefaults[self.ANNOTATIONTYPE].keys())[0] != self.set:
if self.set != None:
if self.ANNOTATIONTYPE in self.doc.set_alias and self.set in self.doc.set_alias[self.ANNOTATIONTYPE]:
attribs['{' + NSFOLIA + '}set'] = self.doc.set_alias[self.ANNOTATIONTYPE][self.set] #use alias instead
else:
attribs['{' + NSFOLIA + '}set'] = self.set
except AttributeError:
pass
if '{' + NSFOLIA + '}class' not in attribs: #do not override if caller already set it
try:
if self.cls:
attribs['{' + NSFOLIA + '}class'] = self.cls
except AttributeError:
pass
if '{' + NSFOLIA + '}annotator' not in attribs: #do not override if caller already set it
try:
if self.annotator and ((not (self.ANNOTATIONTYPE in self.doc.annotationdefaults)) or (not ( 'annotator' in self.doc.annotationdefaults[self.ANNOTATIONTYPE][self.set])) or (self.annotator != self.doc.annotationdefaults[self.ANNOTATIONTYPE][self.set]['annotator'])):
attribs['{' + NSFOLIA + '}annotator'] = self.annotator
if self.annotatortype and ((not (self.ANNOTATIONTYPE in self.doc.annotationdefaults)) or (not ('annotatortype' in self.doc.annotationdefaults[self.ANNOTATIONTYPE][self.set])) or (self.annotatortype != self.doc.annotationdefaults[self.ANNOTATIONTYPE][self.set]['annotatortype'])):
if self.annotatortype == AnnotatorType.AUTO:
attribs['{' + NSFOLIA + '}annotatortype'] = 'auto'
elif self.annotatortype == AnnotatorType.MANUAL:
attribs['{' + NSFOLIA + '}annotatortype'] = 'manual'
except AttributeError:
pass
if '{' + NSFOLIA + '}confidence' not in attribs: #do not override if caller already set it
if self.confidence:
attribs['{' + NSFOLIA + '}confidence'] = str(self.confidence)
if '{' + NSFOLIA + '}n' not in attribs: #do not override if caller already set it
if self.n:
attribs['{' + NSFOLIA + '}n'] = str(self.n)
if '{' + NSFOLIA + '}auth' not in attribs: #do not override if caller already set it
try:
if not self.AUTH or not self.auth: #(former is static, latter isn't)
attribs['{' + NSFOLIA + '}auth'] = 'no'
except AttributeError:
pass
if '{' + NSFOLIA + '}datetime' not in attribs: #do not override if caller already set it
if self.datetime and ((not (self.ANNOTATIONTYPE in self.doc.annotationdefaults)) or (not ( 'datetime' in self.doc.annotationdefaults[self.ANNOTATIONTYPE][self.set])) or (self.datetime != self.doc.annotationdefaults[self.ANNOTATIONTYPE][self.set]['datetime'])):
attribs['{' + NSFOLIA + '}datetime'] = self.datetime.strftime("%Y-%m-%dT%H:%M:%S")
if '{' + NSFOLIA + '}src' not in attribs: #do not override if caller already set it
if self.src:
attribs['{' + NSFOLIA + '}src'] = self.src
if '{' + NSFOLIA + '}speaker' not in attribs: #do not override if caller already set it
if self.speaker:
attribs['{' + NSFOLIA + '}speaker'] = self.speaker
if '{' + NSFOLIA + '}begintime' not in attribs: #do not override if caller already set it
if self.begintime:
attribs['{' + NSFOLIA + '}begintime'] = "%02d:%02d:%02d.%03d" % self.begintime
if '{' + NSFOLIA + '}endtime' not in attribs: #do not override if caller already set it
if self.endtime:
attribs['{' + NSFOLIA + '}endtime'] = "%02d:%02d:%02d.%03d" % self.endtime
if '{' + NSFOLIA + '}textclass' not in attribs: #do not override if caller already set it
if self.textclass and self.textclass != "current":
attribs['{' + NSFOLIA + '}textclass'] = self.textclass
if '{' + NSFOLIA + '}metadata' not in attribs: #do not override if caller already set it
if self.metadata:
attribs['{' + NSFOLIA + '}metadata'] = self.metadata
if self.XLINK:
if self.href:
attribs['{http://www.w3.org/1999/xlink}href'] = self.href
if not self.xlinktype:
attribs['{http://www.w3.org/1999/xlink}type'] = "simple"
if self.xlinktype:
attribs['{http://www.w3.org/1999/xlink}type'] = self.xlinktype
if self.xlinklabel:
attribs['{http://www.w3.org/1999/xlink}label'] = self.xlinklabel
if self.xlinkrole:
attribs['{http://www.w3.org/1999/xlink}role'] = self.xlinkrole
if self.xlinkshow:
attribs['{http://www.w3.org/1999/xlink}show'] = self.xlinkshow
if self.xlinktitle:
attribs['{http://www.w3.org/1999/xlink}title'] = self.xlinktitle
omitchildren = []
#Are there predetermined Features in ACCEPTED_DATA?
for c in self.ACCEPTED_DATA:
if issubclass(c, Feature) and c.SUBSET:
#Do we have any of those?
for c2 in self.data:
if c2.__class__ is c and c.SUBSET == c2.SUBSET and c2.cls:
#Yes, serialize them as attributes
attribs[c2.SUBSET] = c2.cls
omitchildren.append(c2) #and skip them as elements
break #only one
e = makeelement(E, '{' + NSFOLIA + '}' + self.XMLTAG, **attribs)
if not skipchildren and self.data:
#append children,
# we want make sure that text elements are in the right order, 'current' class first
# so we first put them in a list
textelements = []
otherelements = []
for child in self:
if isinstance(child, TextContent):
if child.cls == 'current':
textelements.insert(0, child)
else:
textelements.append(child)
elif not child in omitchildren:
otherelements.append(child)
for child in textelements+otherelements:
if (self.TEXTCONTAINER or self.PHONCONTAINER) and isstring(child):
if len(e) == 0:
if e.text:
e.text += child
else:
e.text = child
else:
#add to tail of last child
if e[-1].tail:
e[-1].tail += child
else:
e[-1].tail = child
else:
xml = child.xml() #may return None in rare occassions, meaning we wan to skip
if not xml is None:
e.append(xml)
if elements: #extra elements
for e2 in elements:
if isinstance(e2, str) or (sys.version < '3' and isinstance(e2, unicode)):
if e.text is None:
e.text = e2
else:
e.text += e2
else:
e.append(e2)
return e | python | def xml(self, attribs = None,elements = None, skipchildren = False):
"""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
"""
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.w3.org/XML/1998/namespace}id'] = self.id
#Some attributes only need to be added if they are not the same as what's already set in the declaration
if not isinstance(self, AbstractAnnotationLayer):
if '{' + NSFOLIA + '}set' not in attribs: #do not override if overloaded function already set it
try:
if self.set:
if not self.ANNOTATIONTYPE in self.doc.annotationdefaults or len(self.doc.annotationdefaults[self.ANNOTATIONTYPE]) != 1 or list(self.doc.annotationdefaults[self.ANNOTATIONTYPE].keys())[0] != self.set:
if self.set != None:
if self.ANNOTATIONTYPE in self.doc.set_alias and self.set in self.doc.set_alias[self.ANNOTATIONTYPE]:
attribs['{' + NSFOLIA + '}set'] = self.doc.set_alias[self.ANNOTATIONTYPE][self.set] #use alias instead
else:
attribs['{' + NSFOLIA + '}set'] = self.set
except AttributeError:
pass
if '{' + NSFOLIA + '}class' not in attribs: #do not override if caller already set it
try:
if self.cls:
attribs['{' + NSFOLIA + '}class'] = self.cls
except AttributeError:
pass
if '{' + NSFOLIA + '}annotator' not in attribs: #do not override if caller already set it
try:
if self.annotator and ((not (self.ANNOTATIONTYPE in self.doc.annotationdefaults)) or (not ( 'annotator' in self.doc.annotationdefaults[self.ANNOTATIONTYPE][self.set])) or (self.annotator != self.doc.annotationdefaults[self.ANNOTATIONTYPE][self.set]['annotator'])):
attribs['{' + NSFOLIA + '}annotator'] = self.annotator
if self.annotatortype and ((not (self.ANNOTATIONTYPE in self.doc.annotationdefaults)) or (not ('annotatortype' in self.doc.annotationdefaults[self.ANNOTATIONTYPE][self.set])) or (self.annotatortype != self.doc.annotationdefaults[self.ANNOTATIONTYPE][self.set]['annotatortype'])):
if self.annotatortype == AnnotatorType.AUTO:
attribs['{' + NSFOLIA + '}annotatortype'] = 'auto'
elif self.annotatortype == AnnotatorType.MANUAL:
attribs['{' + NSFOLIA + '}annotatortype'] = 'manual'
except AttributeError:
pass
if '{' + NSFOLIA + '}confidence' not in attribs: #do not override if caller already set it
if self.confidence:
attribs['{' + NSFOLIA + '}confidence'] = str(self.confidence)
if '{' + NSFOLIA + '}n' not in attribs: #do not override if caller already set it
if self.n:
attribs['{' + NSFOLIA + '}n'] = str(self.n)
if '{' + NSFOLIA + '}auth' not in attribs: #do not override if caller already set it
try:
if not self.AUTH or not self.auth: #(former is static, latter isn't)
attribs['{' + NSFOLIA + '}auth'] = 'no'
except AttributeError:
pass
if '{' + NSFOLIA + '}datetime' not in attribs: #do not override if caller already set it
if self.datetime and ((not (self.ANNOTATIONTYPE in self.doc.annotationdefaults)) or (not ( 'datetime' in self.doc.annotationdefaults[self.ANNOTATIONTYPE][self.set])) or (self.datetime != self.doc.annotationdefaults[self.ANNOTATIONTYPE][self.set]['datetime'])):
attribs['{' + NSFOLIA + '}datetime'] = self.datetime.strftime("%Y-%m-%dT%H:%M:%S")
if '{' + NSFOLIA + '}src' not in attribs: #do not override if caller already set it
if self.src:
attribs['{' + NSFOLIA + '}src'] = self.src
if '{' + NSFOLIA + '}speaker' not in attribs: #do not override if caller already set it
if self.speaker:
attribs['{' + NSFOLIA + '}speaker'] = self.speaker
if '{' + NSFOLIA + '}begintime' not in attribs: #do not override if caller already set it
if self.begintime:
attribs['{' + NSFOLIA + '}begintime'] = "%02d:%02d:%02d.%03d" % self.begintime
if '{' + NSFOLIA + '}endtime' not in attribs: #do not override if caller already set it
if self.endtime:
attribs['{' + NSFOLIA + '}endtime'] = "%02d:%02d:%02d.%03d" % self.endtime
if '{' + NSFOLIA + '}textclass' not in attribs: #do not override if caller already set it
if self.textclass and self.textclass != "current":
attribs['{' + NSFOLIA + '}textclass'] = self.textclass
if '{' + NSFOLIA + '}metadata' not in attribs: #do not override if caller already set it
if self.metadata:
attribs['{' + NSFOLIA + '}metadata'] = self.metadata
if self.XLINK:
if self.href:
attribs['{http://www.w3.org/1999/xlink}href'] = self.href
if not self.xlinktype:
attribs['{http://www.w3.org/1999/xlink}type'] = "simple"
if self.xlinktype:
attribs['{http://www.w3.org/1999/xlink}type'] = self.xlinktype
if self.xlinklabel:
attribs['{http://www.w3.org/1999/xlink}label'] = self.xlinklabel
if self.xlinkrole:
attribs['{http://www.w3.org/1999/xlink}role'] = self.xlinkrole
if self.xlinkshow:
attribs['{http://www.w3.org/1999/xlink}show'] = self.xlinkshow
if self.xlinktitle:
attribs['{http://www.w3.org/1999/xlink}title'] = self.xlinktitle
omitchildren = []
#Are there predetermined Features in ACCEPTED_DATA?
for c in self.ACCEPTED_DATA:
if issubclass(c, Feature) and c.SUBSET:
#Do we have any of those?
for c2 in self.data:
if c2.__class__ is c and c.SUBSET == c2.SUBSET and c2.cls:
#Yes, serialize them as attributes
attribs[c2.SUBSET] = c2.cls
omitchildren.append(c2) #and skip them as elements
break #only one
e = makeelement(E, '{' + NSFOLIA + '}' + self.XMLTAG, **attribs)
if not skipchildren and self.data:
#append children,
# we want make sure that text elements are in the right order, 'current' class first
# so we first put them in a list
textelements = []
otherelements = []
for child in self:
if isinstance(child, TextContent):
if child.cls == 'current':
textelements.insert(0, child)
else:
textelements.append(child)
elif not child in omitchildren:
otherelements.append(child)
for child in textelements+otherelements:
if (self.TEXTCONTAINER or self.PHONCONTAINER) and isstring(child):
if len(e) == 0:
if e.text:
e.text += child
else:
e.text = child
else:
#add to tail of last child
if e[-1].tail:
e[-1].tail += child
else:
e[-1].tail = child
else:
xml = child.xml() #may return None in rare occassions, meaning we wan to skip
if not xml is None:
e.append(xml)
if elements: #extra elements
for e2 in elements:
if isinstance(e2, str) or (sys.version < '3' and isinstance(e2, unicode)):
if e.text is None:
e.text = e2
else:
e.text += e2
else:
e.append(e2)
return e | [
"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.w3.org/XML/1998/namespace}id'",
"]",
"=",
"self",
".",
"id",
"#Some attributes only need to be added if they are not the same as what's already set in the declaration",
"if",
"not",
"isinstance",
"(",
"self",
",",
"AbstractAnnotationLayer",
")",
":",
"if",
"'{'",
"+",
"NSFOLIA",
"+",
"'}set'",
"not",
"in",
"attribs",
":",
"#do not override if overloaded function already set it",
"try",
":",
"if",
"self",
".",
"set",
":",
"if",
"not",
"self",
".",
"ANNOTATIONTYPE",
"in",
"self",
".",
"doc",
".",
"annotationdefaults",
"or",
"len",
"(",
"self",
".",
"doc",
".",
"annotationdefaults",
"[",
"self",
".",
"ANNOTATIONTYPE",
"]",
")",
"!=",
"1",
"or",
"list",
"(",
"self",
".",
"doc",
".",
"annotationdefaults",
"[",
"self",
".",
"ANNOTATIONTYPE",
"]",
".",
"keys",
"(",
")",
")",
"[",
"0",
"]",
"!=",
"self",
".",
"set",
":",
"if",
"self",
".",
"set",
"!=",
"None",
":",
"if",
"self",
".",
"ANNOTATIONTYPE",
"in",
"self",
".",
"doc",
".",
"set_alias",
"and",
"self",
".",
"set",
"in",
"self",
".",
"doc",
".",
"set_alias",
"[",
"self",
".",
"ANNOTATIONTYPE",
"]",
":",
"attribs",
"[",
"'{'",
"+",
"NSFOLIA",
"+",
"'}set'",
"]",
"=",
"self",
".",
"doc",
".",
"set_alias",
"[",
"self",
".",
"ANNOTATIONTYPE",
"]",
"[",
"self",
".",
"set",
"]",
"#use alias instead",
"else",
":",
"attribs",
"[",
"'{'",
"+",
"NSFOLIA",
"+",
"'}set'",
"]",
"=",
"self",
".",
"set",
"except",
"AttributeError",
":",
"pass",
"if",
"'{'",
"+",
"NSFOLIA",
"+",
"'}class'",
"not",
"in",
"attribs",
":",
"#do not override if caller already set it",
"try",
":",
"if",
"self",
".",
"cls",
":",
"attribs",
"[",
"'{'",
"+",
"NSFOLIA",
"+",
"'}class'",
"]",
"=",
"self",
".",
"cls",
"except",
"AttributeError",
":",
"pass",
"if",
"'{'",
"+",
"NSFOLIA",
"+",
"'}annotator'",
"not",
"in",
"attribs",
":",
"#do not override if caller already set it",
"try",
":",
"if",
"self",
".",
"annotator",
"and",
"(",
"(",
"not",
"(",
"self",
".",
"ANNOTATIONTYPE",
"in",
"self",
".",
"doc",
".",
"annotationdefaults",
")",
")",
"or",
"(",
"not",
"(",
"'annotator'",
"in",
"self",
".",
"doc",
".",
"annotationdefaults",
"[",
"self",
".",
"ANNOTATIONTYPE",
"]",
"[",
"self",
".",
"set",
"]",
")",
")",
"or",
"(",
"self",
".",
"annotator",
"!=",
"self",
".",
"doc",
".",
"annotationdefaults",
"[",
"self",
".",
"ANNOTATIONTYPE",
"]",
"[",
"self",
".",
"set",
"]",
"[",
"'annotator'",
"]",
")",
")",
":",
"attribs",
"[",
"'{'",
"+",
"NSFOLIA",
"+",
"'}annotator'",
"]",
"=",
"self",
".",
"annotator",
"if",
"self",
".",
"annotatortype",
"and",
"(",
"(",
"not",
"(",
"self",
".",
"ANNOTATIONTYPE",
"in",
"self",
".",
"doc",
".",
"annotationdefaults",
")",
")",
"or",
"(",
"not",
"(",
"'annotatortype'",
"in",
"self",
".",
"doc",
".",
"annotationdefaults",
"[",
"self",
".",
"ANNOTATIONTYPE",
"]",
"[",
"self",
".",
"set",
"]",
")",
")",
"or",
"(",
"self",
".",
"annotatortype",
"!=",
"self",
".",
"doc",
".",
"annotationdefaults",
"[",
"self",
".",
"ANNOTATIONTYPE",
"]",
"[",
"self",
".",
"set",
"]",
"[",
"'annotatortype'",
"]",
")",
")",
":",
"if",
"self",
".",
"annotatortype",
"==",
"AnnotatorType",
".",
"AUTO",
":",
"attribs",
"[",
"'{'",
"+",
"NSFOLIA",
"+",
"'}annotatortype'",
"]",
"=",
"'auto'",
"elif",
"self",
".",
"annotatortype",
"==",
"AnnotatorType",
".",
"MANUAL",
":",
"attribs",
"[",
"'{'",
"+",
"NSFOLIA",
"+",
"'}annotatortype'",
"]",
"=",
"'manual'",
"except",
"AttributeError",
":",
"pass",
"if",
"'{'",
"+",
"NSFOLIA",
"+",
"'}confidence'",
"not",
"in",
"attribs",
":",
"#do not override if caller already set it",
"if",
"self",
".",
"confidence",
":",
"attribs",
"[",
"'{'",
"+",
"NSFOLIA",
"+",
"'}confidence'",
"]",
"=",
"str",
"(",
"self",
".",
"confidence",
")",
"if",
"'{'",
"+",
"NSFOLIA",
"+",
"'}n'",
"not",
"in",
"attribs",
":",
"#do not override if caller already set it",
"if",
"self",
".",
"n",
":",
"attribs",
"[",
"'{'",
"+",
"NSFOLIA",
"+",
"'}n'",
"]",
"=",
"str",
"(",
"self",
".",
"n",
")",
"if",
"'{'",
"+",
"NSFOLIA",
"+",
"'}auth'",
"not",
"in",
"attribs",
":",
"#do not override if caller already set it",
"try",
":",
"if",
"not",
"self",
".",
"AUTH",
"or",
"not",
"self",
".",
"auth",
":",
"#(former is static, latter isn't)",
"attribs",
"[",
"'{'",
"+",
"NSFOLIA",
"+",
"'}auth'",
"]",
"=",
"'no'",
"except",
"AttributeError",
":",
"pass",
"if",
"'{'",
"+",
"NSFOLIA",
"+",
"'}datetime'",
"not",
"in",
"attribs",
":",
"#do not override if caller already set it",
"if",
"self",
".",
"datetime",
"and",
"(",
"(",
"not",
"(",
"self",
".",
"ANNOTATIONTYPE",
"in",
"self",
".",
"doc",
".",
"annotationdefaults",
")",
")",
"or",
"(",
"not",
"(",
"'datetime'",
"in",
"self",
".",
"doc",
".",
"annotationdefaults",
"[",
"self",
".",
"ANNOTATIONTYPE",
"]",
"[",
"self",
".",
"set",
"]",
")",
")",
"or",
"(",
"self",
".",
"datetime",
"!=",
"self",
".",
"doc",
".",
"annotationdefaults",
"[",
"self",
".",
"ANNOTATIONTYPE",
"]",
"[",
"self",
".",
"set",
"]",
"[",
"'datetime'",
"]",
")",
")",
":",
"attribs",
"[",
"'{'",
"+",
"NSFOLIA",
"+",
"'}datetime'",
"]",
"=",
"self",
".",
"datetime",
".",
"strftime",
"(",
"\"%Y-%m-%dT%H:%M:%S\"",
")",
"if",
"'{'",
"+",
"NSFOLIA",
"+",
"'}src'",
"not",
"in",
"attribs",
":",
"#do not override if caller already set it",
"if",
"self",
".",
"src",
":",
"attribs",
"[",
"'{'",
"+",
"NSFOLIA",
"+",
"'}src'",
"]",
"=",
"self",
".",
"src",
"if",
"'{'",
"+",
"NSFOLIA",
"+",
"'}speaker'",
"not",
"in",
"attribs",
":",
"#do not override if caller already set it",
"if",
"self",
".",
"speaker",
":",
"attribs",
"[",
"'{'",
"+",
"NSFOLIA",
"+",
"'}speaker'",
"]",
"=",
"self",
".",
"speaker",
"if",
"'{'",
"+",
"NSFOLIA",
"+",
"'}begintime'",
"not",
"in",
"attribs",
":",
"#do not override if caller already set it",
"if",
"self",
".",
"begintime",
":",
"attribs",
"[",
"'{'",
"+",
"NSFOLIA",
"+",
"'}begintime'",
"]",
"=",
"\"%02d:%02d:%02d.%03d\"",
"%",
"self",
".",
"begintime",
"if",
"'{'",
"+",
"NSFOLIA",
"+",
"'}endtime'",
"not",
"in",
"attribs",
":",
"#do not override if caller already set it",
"if",
"self",
".",
"endtime",
":",
"attribs",
"[",
"'{'",
"+",
"NSFOLIA",
"+",
"'}endtime'",
"]",
"=",
"\"%02d:%02d:%02d.%03d\"",
"%",
"self",
".",
"endtime",
"if",
"'{'",
"+",
"NSFOLIA",
"+",
"'}textclass'",
"not",
"in",
"attribs",
":",
"#do not override if caller already set it",
"if",
"self",
".",
"textclass",
"and",
"self",
".",
"textclass",
"!=",
"\"current\"",
":",
"attribs",
"[",
"'{'",
"+",
"NSFOLIA",
"+",
"'}textclass'",
"]",
"=",
"self",
".",
"textclass",
"if",
"'{'",
"+",
"NSFOLIA",
"+",
"'}metadata'",
"not",
"in",
"attribs",
":",
"#do not override if caller already set it",
"if",
"self",
".",
"metadata",
":",
"attribs",
"[",
"'{'",
"+",
"NSFOLIA",
"+",
"'}metadata'",
"]",
"=",
"self",
".",
"metadata",
"if",
"self",
".",
"XLINK",
":",
"if",
"self",
".",
"href",
":",
"attribs",
"[",
"'{http://www.w3.org/1999/xlink}href'",
"]",
"=",
"self",
".",
"href",
"if",
"not",
"self",
".",
"xlinktype",
":",
"attribs",
"[",
"'{http://www.w3.org/1999/xlink}type'",
"]",
"=",
"\"simple\"",
"if",
"self",
".",
"xlinktype",
":",
"attribs",
"[",
"'{http://www.w3.org/1999/xlink}type'",
"]",
"=",
"self",
".",
"xlinktype",
"if",
"self",
".",
"xlinklabel",
":",
"attribs",
"[",
"'{http://www.w3.org/1999/xlink}label'",
"]",
"=",
"self",
".",
"xlinklabel",
"if",
"self",
".",
"xlinkrole",
":",
"attribs",
"[",
"'{http://www.w3.org/1999/xlink}role'",
"]",
"=",
"self",
".",
"xlinkrole",
"if",
"self",
".",
"xlinkshow",
":",
"attribs",
"[",
"'{http://www.w3.org/1999/xlink}show'",
"]",
"=",
"self",
".",
"xlinkshow",
"if",
"self",
".",
"xlinktitle",
":",
"attribs",
"[",
"'{http://www.w3.org/1999/xlink}title'",
"]",
"=",
"self",
".",
"xlinktitle",
"omitchildren",
"=",
"[",
"]",
"#Are there predetermined Features in ACCEPTED_DATA?",
"for",
"c",
"in",
"self",
".",
"ACCEPTED_DATA",
":",
"if",
"issubclass",
"(",
"c",
",",
"Feature",
")",
"and",
"c",
".",
"SUBSET",
":",
"#Do we have any of those?",
"for",
"c2",
"in",
"self",
".",
"data",
":",
"if",
"c2",
".",
"__class__",
"is",
"c",
"and",
"c",
".",
"SUBSET",
"==",
"c2",
".",
"SUBSET",
"and",
"c2",
".",
"cls",
":",
"#Yes, serialize them as attributes",
"attribs",
"[",
"c2",
".",
"SUBSET",
"]",
"=",
"c2",
".",
"cls",
"omitchildren",
".",
"append",
"(",
"c2",
")",
"#and skip them as elements",
"break",
"#only one",
"e",
"=",
"makeelement",
"(",
"E",
",",
"'{'",
"+",
"NSFOLIA",
"+",
"'}'",
"+",
"self",
".",
"XMLTAG",
",",
"*",
"*",
"attribs",
")",
"if",
"not",
"skipchildren",
"and",
"self",
".",
"data",
":",
"#append children,",
"# we want make sure that text elements are in the right order, 'current' class first",
"# so we first put them in a list",
"textelements",
"=",
"[",
"]",
"otherelements",
"=",
"[",
"]",
"for",
"child",
"in",
"self",
":",
"if",
"isinstance",
"(",
"child",
",",
"TextContent",
")",
":",
"if",
"child",
".",
"cls",
"==",
"'current'",
":",
"textelements",
".",
"insert",
"(",
"0",
",",
"child",
")",
"else",
":",
"textelements",
".",
"append",
"(",
"child",
")",
"elif",
"not",
"child",
"in",
"omitchildren",
":",
"otherelements",
".",
"append",
"(",
"child",
")",
"for",
"child",
"in",
"textelements",
"+",
"otherelements",
":",
"if",
"(",
"self",
".",
"TEXTCONTAINER",
"or",
"self",
".",
"PHONCONTAINER",
")",
"and",
"isstring",
"(",
"child",
")",
":",
"if",
"len",
"(",
"e",
")",
"==",
"0",
":",
"if",
"e",
".",
"text",
":",
"e",
".",
"text",
"+=",
"child",
"else",
":",
"e",
".",
"text",
"=",
"child",
"else",
":",
"#add to tail of last child",
"if",
"e",
"[",
"-",
"1",
"]",
".",
"tail",
":",
"e",
"[",
"-",
"1",
"]",
".",
"tail",
"+=",
"child",
"else",
":",
"e",
"[",
"-",
"1",
"]",
".",
"tail",
"=",
"child",
"else",
":",
"xml",
"=",
"child",
".",
"xml",
"(",
")",
"#may return None in rare occassions, meaning we wan to skip",
"if",
"not",
"xml",
"is",
"None",
":",
"e",
".",
"append",
"(",
"xml",
")",
"if",
"elements",
":",
"#extra elements",
"for",
"e2",
"in",
"elements",
":",
"if",
"isinstance",
"(",
"e2",
",",
"str",
")",
"or",
"(",
"sys",
".",
"version",
"<",
"'3'",
"and",
"isinstance",
"(",
"e2",
",",
"unicode",
")",
")",
":",
"if",
"e",
".",
"text",
"is",
"None",
":",
"e",
".",
"text",
"=",
"e2",
"else",
":",
"e",
".",
"text",
"+=",
"e2",
"else",
":",
"e",
".",
"append",
"(",
"e2",
")",
"return",
"e"
] | 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 | [
"Serialises",
"the",
"FoLiA",
"element",
"and",
"all",
"its",
"contents",
"to",
"XML",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1877-L2047 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.json | 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
"""
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 | python | 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
"""
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",
")",
":",
"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"
] | 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 | [
"Serialises",
"the",
"FoLiA",
"element",
"and",
"all",
"its",
"contents",
"to",
"a",
"Python",
"dictionary",
"suitable",
"for",
"serialisation",
"to",
"JSON",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L2050-L2110 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.xmlstring | 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"""
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 | python | 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"""
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",
")",
":",
"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"
] | Serialises this FoLiA element and all its contents to XML.
Returns:
str: a string with XML representation for this element and all its children | [
"Serialises",
"this",
"FoLiA",
"element",
"and",
"all",
"its",
"contents",
"to",
"XML",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L2114-L2129 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.select | def select(self, Class, set=None, recursive=True, ignore=True, node=None): #pylint: disable=bad-classmethod-argument,redefined-builtin
"""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] ):
..
"""
#if ignorelist is True:
# 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 | python | def select(self, Class, set=None, recursive=True, ignore=True, node=None): #pylint: disable=bad-classmethod-argument,redefined-builtin
"""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] ):
..
"""
#if ignorelist is True:
# 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:",
"# 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"
] | 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] ):
.. | [
"Select",
"child",
"elements",
"of",
"the",
"specified",
"class",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L2132-L2201 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.count | 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
"""
return sum(1 for i in self.select(Class,set,recursive,ignore,node) ) | python | 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
"""
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",
")",
":",
"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 | [
"Like",
":",
"meth",
":",
"AbstractElement",
".",
"select",
"but",
"instead",
"of",
"returning",
"the",
"elements",
"it",
"merely",
"counts",
"them",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L2203-L2209 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.items | def items(self, founditems=[]): #pylint: disable=dangerous-default-value
"""Returns a depth-first flat list of *all* items below this element (not limited to AbstractElement)"""
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)
return l | python | def items(self, founditems=[]): #pylint: disable=dangerous-default-value
"""Returns a depth-first flat list of *all* items below this element (not limited to AbstractElement)"""
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)
return l | [
"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",
")",
"return",
"l"
] | Returns a depth-first flat list of *all* items below this element (not limited to AbstractElement) | [
"Returns",
"a",
"depth",
"-",
"first",
"flat",
"list",
"of",
"*",
"all",
"*",
"items",
"below",
"this",
"element",
"(",
"not",
"limited",
"to",
"AbstractElement",
")"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L2211-L2219 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.getmetadata | def getmetadata(self, key=None):
"""Get the metadata that applies to this element, automatically inherited from parent elements"""
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 | python | def getmetadata(self, key=None):
"""Get the metadata that applies to this element, automatically inherited from parent elements"""
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",
")",
":",
"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"
] | Get the metadata that applies to this element, automatically inherited from parent elements | [
"Get",
"the",
"metadata",
"that",
"applies",
"to",
"this",
"element",
"automatically",
"inherited",
"from",
"parent",
"elements"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L2221-L2234 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.getindex | def getindex(self, child, recursive=True, ignore=True):
"""Get the index at which an element occurs, recursive by default!
Returns:
int
"""
#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 | python | def getindex(self, child, recursive=True, ignore=True):
"""Get the index at which an element occurs, recursive by default!
Returns:
int
"""
#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",
")",
":",
"#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"
] | Get the index at which an element occurs, recursive by default!
Returns:
int | [
"Get",
"the",
"index",
"at",
"which",
"an",
"element",
"occurs",
"recursive",
"by",
"default!"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L2238-L2278 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.precedes | def precedes(self, other):
"""Returns a boolean indicating whether this element precedes the other element"""
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 | python | def precedes(self, other):
"""Returns a boolean indicating whether this element precedes the other element"""
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",
")",
":",
"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"
] | Returns a boolean indicating whether this element precedes the other element | [
"Returns",
"a",
"boolean",
"indicating",
"whether",
"this",
"element",
"precedes",
"the",
"other",
"element"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L2280-L2296 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.depthfirstsearch | def depthfirstsearch(self, function):
"""Generic depth first search algorithm using a callback function, continues as long as the callback function returns None"""
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 | python | def depthfirstsearch(self, function):
"""Generic depth first search algorithm using a callback function, continues as long as the callback function returns None"""
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",
")",
":",
"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 | [
"Generic",
"depth",
"first",
"search",
"algorithm",
"using",
"a",
"callback",
"function",
"continues",
"as",
"long",
"as",
"the",
"callback",
"function",
"returns",
"None"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L2299-L2308 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.next | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | 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. | [
"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",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L2310-L2367 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.previous | 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.
"""
return self.next(Class,scope, True) | python | 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.
"""
return self.next(Class,scope, True) | [
"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 `'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. | [
"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",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L2371-L2379 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.leftcontext | 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"""
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 | python | 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"""
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",
")",
":",
"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"
] | 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 | [
"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"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L2381-L2398 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.rightcontext | 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"""
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 | python | 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"""
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",
")",
":",
"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"
] | 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 | [
"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"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L2401-L2417 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.context | 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"""
return self.leftcontext(size, placeholder,scope) + [self] + self.rightcontext(size, placeholder,scope) | python | 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"""
return self.leftcontext(size, placeholder,scope) + [self] + self.rightcontext(size, placeholder,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 | [
"Returns",
"this",
"word",
"in",
"context",
"{",
"size",
"}",
"words",
"to",
"the",
"left",
"the",
"current",
"word",
"and",
"{",
"size",
"}",
"words",
"to",
"the",
"right"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L2419-L2421 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.relaxng | 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)"""
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 origclass: cls = origclass
preamble = []
try:
if cls.__doc__:
E2 = ElementMaker(namespace="http://relaxng.org/ns/annotation/0.9", nsmap={'a':'http://relaxng.org/ns/annotation/0.9'} )
preamble.append(E2.documentation(cls.__doc__))
except AttributeError:
pass
if cls.REQUIRED_ATTRIBS is None: cls.REQUIRED_ATTRIBS = () #bit hacky
if cls.OPTIONAL_ATTRIBS is None: cls.OPTIONAL_ATTRIBS = () #bit hacky
attribs = [ ]
if cls.REQUIRED_ATTRIBS and Attrib.ID in cls.REQUIRED_ATTRIBS:
attribs.append( E.attribute(E.data(type='ID',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='id', ns="http://www.w3.org/XML/1998/namespace") )
elif Attrib.ID in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute(E.data(type='ID',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='id', ns="http://www.w3.org/XML/1998/namespace") ) )
if Attrib.CLASS in cls.REQUIRED_ATTRIBS:
#Set is a tough one, we can't require it as it may be defined in the declaration: we make it optional and need schematron to resolve this later
attribs.append( E.attribute(E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='class') )
attribs.append( E.optional( E.attribute( E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='set' ) ) )
elif Attrib.CLASS in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute(E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='class') ) )
attribs.append( E.optional( E.attribute(E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='set' ) ) )
if Attrib.ANNOTATOR in cls.REQUIRED_ATTRIBS or Attrib.ANNOTATOR in cls.OPTIONAL_ATTRIBS:
#Similarly tough
attribs.append( E.optional( E.attribute(E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='annotator') ) )
attribs.append( E.optional( E.attribute(name='annotatortype') ) )
if Attrib.CONFIDENCE in cls.REQUIRED_ATTRIBS:
attribs.append( E.attribute(E.data(type='double',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='confidence') )
elif Attrib.CONFIDENCE in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute(E.data(type='double',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='confidence') ) )
if Attrib.N in cls.REQUIRED_ATTRIBS:
attribs.append( E.attribute( E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='n') )
elif Attrib.N in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute( E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='n') ) )
if Attrib.DATETIME in cls.REQUIRED_ATTRIBS:
attribs.append( E.attribute(E.data(type='dateTime',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='datetime') )
elif Attrib.DATETIME in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute( E.data(type='dateTime',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='datetime') ) )
if Attrib.BEGINTIME in cls.REQUIRED_ATTRIBS:
attribs.append(E.attribute(name='begintime') )
elif Attrib.BEGINTIME in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute(name='begintime') ) )
if Attrib.ENDTIME in cls.REQUIRED_ATTRIBS:
attribs.append(E.attribute(name='endtime') )
elif Attrib.ENDTIME in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute(name='endtime') ) )
if Attrib.SRC in cls.REQUIRED_ATTRIBS:
attribs.append(E.attribute(E.data(type='anyURI',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='src') )
elif Attrib.SRC in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute(E.data(type='anyURI',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='src') ) )
if Attrib.SPEAKER in cls.REQUIRED_ATTRIBS:
attribs.append(E.attribute(E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='speaker') )
elif Attrib.SPEAKER in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute(E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='speaker') ) )
if Attrib.TEXTCLASS in cls.REQUIRED_ATTRIBS:
attribs.append(E.attribute(name='textclass') )
elif Attrib.TEXTCLASS in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute(name='textclass') ) )
if Attrib.METADATA in cls.REQUIRED_ATTRIBS:
attribs.append(E.attribute(name='metadata') )
elif Attrib.METADATA in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute(name='metadata') ) )
if cls.XLINK:
attribs += [ #loose interpretation of specs, not checking whether xlink combinations are valid
E.optional(E.attribute(name='href',ns="http://www.w3.org/1999/xlink"),E.attribute(name='type',ns="http://www.w3.org/1999/xlink") ),
E.optional(E.attribute(name='role',ns="http://www.w3.org/1999/xlink")),
E.optional(E.attribute(name='title',ns="http://www.w3.org/1999/xlink")),
E.optional(E.attribute(name='label',ns="http://www.w3.org/1999/xlink")),
E.optional(E.attribute(name='show',ns="http://www.w3.org/1999/xlink")),
]
attribs.append( E.optional( E.attribute( name='auth' ) ) )
if extraattribs:
for e in extraattribs:
attribs.append(e) #s
attribs.append( E.ref(name="allow_foreign_attributes") )
elements = [] #(including attributes)
if cls.TEXTCONTAINER or cls.PHONCONTAINER:
elements.append( E.text())
#We actually want to require non-empty text (E.text() is not sufficient)
#but this is not solved yet, see https://github.com/proycon/folia/issues/19
#elements.append( E.data(E.param(r".+",name="pattern"),type='string'))
#elements.append( E.data(E.param(r"(.|\n|\r)*\S+(.|\n|\r)*",name="pattern"),type='string'))
done = {}
if includechildren and cls.ACCEPTED_DATA: #pylint: disable=too-many-nested-blocks
for c in cls.ACCEPTED_DATA:
if c.__name__[:8] == 'Abstract' and inspect.isclass(c):
for c2 in globals().values():
try:
if inspect.isclass(c2) and issubclass(c2, c):
try:
if c2.XMLTAG and c2.XMLTAG not in done:
if c2.OCCURRENCES == 1:
elements.append( E.optional( E.ref(name=c2.XMLTAG) ) )
else:
elements.append( E.zeroOrMore( E.ref(name=c2.XMLTAG) ) )
if c2.XMLTAG == 'item': #nasty hack for backward compatibility with deprecated listitem element
elements.append( E.zeroOrMore( E.ref(name='listitem') ) )
done[c2.XMLTAG] = True
except AttributeError:
continue
except TypeError:
pass
elif issubclass(c, Feature) and c.SUBSET:
attribs.append( E.optional( E.attribute(name=c.SUBSET))) #features as attributes
else:
try:
if c.XMLTAG and c.XMLTAG not in done:
if cls.REQUIRED_DATA and c in cls.REQUIRED_DATA:
if c.OCCURRENCES == 1:
elements.append( E.ref(name=c.XMLTAG) )
else:
elements.append( E.oneOrMore( E.ref(name=c.XMLTAG) ) )
elif c.OCCURRENCES == 1:
elements.append( E.optional( E.ref(name=c.XMLTAG) ) )
else:
elements.append( E.zeroOrMore( E.ref(name=c.XMLTAG) ) )
if c.XMLTAG == 'item':
#nasty hack for backward compatibility with deprecated listitem element
elements.append( E.zeroOrMore( E.ref(name='listitem') ) )
done[c.XMLTAG] = True
except AttributeError:
continue
if extraelements:
for e in extraelements:
elements.append( e )
if elements:
if len(elements) > 1:
attribs.append( E.interleave(*elements) )
else:
attribs.append( *elements )
if not attribs:
attribs.append( E.empty() )
if cls.XMLTAG in ('desc','comment'):
return E.define( E.element(E.text(), *(preamble + attribs), **{'name': cls.XMLTAG}), name=cls.XMLTAG, ns=NSFOLIA)
else:
return E.define( E.element(*(preamble + attribs), **{'name': cls.XMLTAG}), name=cls.XMLTAG, ns=NSFOLIA) | python | 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)"""
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 origclass: cls = origclass
preamble = []
try:
if cls.__doc__:
E2 = ElementMaker(namespace="http://relaxng.org/ns/annotation/0.9", nsmap={'a':'http://relaxng.org/ns/annotation/0.9'} )
preamble.append(E2.documentation(cls.__doc__))
except AttributeError:
pass
if cls.REQUIRED_ATTRIBS is None: cls.REQUIRED_ATTRIBS = () #bit hacky
if cls.OPTIONAL_ATTRIBS is None: cls.OPTIONAL_ATTRIBS = () #bit hacky
attribs = [ ]
if cls.REQUIRED_ATTRIBS and Attrib.ID in cls.REQUIRED_ATTRIBS:
attribs.append( E.attribute(E.data(type='ID',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='id', ns="http://www.w3.org/XML/1998/namespace") )
elif Attrib.ID in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute(E.data(type='ID',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='id', ns="http://www.w3.org/XML/1998/namespace") ) )
if Attrib.CLASS in cls.REQUIRED_ATTRIBS:
#Set is a tough one, we can't require it as it may be defined in the declaration: we make it optional and need schematron to resolve this later
attribs.append( E.attribute(E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='class') )
attribs.append( E.optional( E.attribute( E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='set' ) ) )
elif Attrib.CLASS in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute(E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='class') ) )
attribs.append( E.optional( E.attribute(E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='set' ) ) )
if Attrib.ANNOTATOR in cls.REQUIRED_ATTRIBS or Attrib.ANNOTATOR in cls.OPTIONAL_ATTRIBS:
#Similarly tough
attribs.append( E.optional( E.attribute(E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='annotator') ) )
attribs.append( E.optional( E.attribute(name='annotatortype') ) )
if Attrib.CONFIDENCE in cls.REQUIRED_ATTRIBS:
attribs.append( E.attribute(E.data(type='double',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='confidence') )
elif Attrib.CONFIDENCE in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute(E.data(type='double',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='confidence') ) )
if Attrib.N in cls.REQUIRED_ATTRIBS:
attribs.append( E.attribute( E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='n') )
elif Attrib.N in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute( E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='n') ) )
if Attrib.DATETIME in cls.REQUIRED_ATTRIBS:
attribs.append( E.attribute(E.data(type='dateTime',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='datetime') )
elif Attrib.DATETIME in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute( E.data(type='dateTime',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='datetime') ) )
if Attrib.BEGINTIME in cls.REQUIRED_ATTRIBS:
attribs.append(E.attribute(name='begintime') )
elif Attrib.BEGINTIME in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute(name='begintime') ) )
if Attrib.ENDTIME in cls.REQUIRED_ATTRIBS:
attribs.append(E.attribute(name='endtime') )
elif Attrib.ENDTIME in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute(name='endtime') ) )
if Attrib.SRC in cls.REQUIRED_ATTRIBS:
attribs.append(E.attribute(E.data(type='anyURI',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='src') )
elif Attrib.SRC in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute(E.data(type='anyURI',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='src') ) )
if Attrib.SPEAKER in cls.REQUIRED_ATTRIBS:
attribs.append(E.attribute(E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'), name='speaker') )
elif Attrib.SPEAKER in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute(E.data(type='string',datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'),name='speaker') ) )
if Attrib.TEXTCLASS in cls.REQUIRED_ATTRIBS:
attribs.append(E.attribute(name='textclass') )
elif Attrib.TEXTCLASS in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute(name='textclass') ) )
if Attrib.METADATA in cls.REQUIRED_ATTRIBS:
attribs.append(E.attribute(name='metadata') )
elif Attrib.METADATA in cls.OPTIONAL_ATTRIBS:
attribs.append( E.optional( E.attribute(name='metadata') ) )
if cls.XLINK:
attribs += [ #loose interpretation of specs, not checking whether xlink combinations are valid
E.optional(E.attribute(name='href',ns="http://www.w3.org/1999/xlink"),E.attribute(name='type',ns="http://www.w3.org/1999/xlink") ),
E.optional(E.attribute(name='role',ns="http://www.w3.org/1999/xlink")),
E.optional(E.attribute(name='title',ns="http://www.w3.org/1999/xlink")),
E.optional(E.attribute(name='label',ns="http://www.w3.org/1999/xlink")),
E.optional(E.attribute(name='show',ns="http://www.w3.org/1999/xlink")),
]
attribs.append( E.optional( E.attribute( name='auth' ) ) )
if extraattribs:
for e in extraattribs:
attribs.append(e) #s
attribs.append( E.ref(name="allow_foreign_attributes") )
elements = [] #(including attributes)
if cls.TEXTCONTAINER or cls.PHONCONTAINER:
elements.append( E.text())
#We actually want to require non-empty text (E.text() is not sufficient)
#but this is not solved yet, see https://github.com/proycon/folia/issues/19
#elements.append( E.data(E.param(r".+",name="pattern"),type='string'))
#elements.append( E.data(E.param(r"(.|\n|\r)*\S+(.|\n|\r)*",name="pattern"),type='string'))
done = {}
if includechildren and cls.ACCEPTED_DATA: #pylint: disable=too-many-nested-blocks
for c in cls.ACCEPTED_DATA:
if c.__name__[:8] == 'Abstract' and inspect.isclass(c):
for c2 in globals().values():
try:
if inspect.isclass(c2) and issubclass(c2, c):
try:
if c2.XMLTAG and c2.XMLTAG not in done:
if c2.OCCURRENCES == 1:
elements.append( E.optional( E.ref(name=c2.XMLTAG) ) )
else:
elements.append( E.zeroOrMore( E.ref(name=c2.XMLTAG) ) )
if c2.XMLTAG == 'item': #nasty hack for backward compatibility with deprecated listitem element
elements.append( E.zeroOrMore( E.ref(name='listitem') ) )
done[c2.XMLTAG] = True
except AttributeError:
continue
except TypeError:
pass
elif issubclass(c, Feature) and c.SUBSET:
attribs.append( E.optional( E.attribute(name=c.SUBSET))) #features as attributes
else:
try:
if c.XMLTAG and c.XMLTAG not in done:
if cls.REQUIRED_DATA and c in cls.REQUIRED_DATA:
if c.OCCURRENCES == 1:
elements.append( E.ref(name=c.XMLTAG) )
else:
elements.append( E.oneOrMore( E.ref(name=c.XMLTAG) ) )
elif c.OCCURRENCES == 1:
elements.append( E.optional( E.ref(name=c.XMLTAG) ) )
else:
elements.append( E.zeroOrMore( E.ref(name=c.XMLTAG) ) )
if c.XMLTAG == 'item':
#nasty hack for backward compatibility with deprecated listitem element
elements.append( E.zeroOrMore( E.ref(name='listitem') ) )
done[c.XMLTAG] = True
except AttributeError:
continue
if extraelements:
for e in extraelements:
elements.append( e )
if elements:
if len(elements) > 1:
attribs.append( E.interleave(*elements) )
else:
attribs.append( *elements )
if not attribs:
attribs.append( E.empty() )
if cls.XMLTAG in ('desc','comment'):
return E.define( E.element(E.text(), *(preamble + attribs), **{'name': cls.XMLTAG}), name=cls.XMLTAG, ns=NSFOLIA)
else:
return E.define( E.element(*(preamble + attribs), **{'name': cls.XMLTAG}), name=cls.XMLTAG, ns=NSFOLIA) | [
"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'",
":",
"\"http://relaxng.org/ns/annotation/0.9\"",
"}",
")",
"if",
"origclass",
":",
"cls",
"=",
"origclass",
"preamble",
"=",
"[",
"]",
"try",
":",
"if",
"cls",
".",
"__doc__",
":",
"E2",
"=",
"ElementMaker",
"(",
"namespace",
"=",
"\"http://relaxng.org/ns/annotation/0.9\"",
",",
"nsmap",
"=",
"{",
"'a'",
":",
"'http://relaxng.org/ns/annotation/0.9'",
"}",
")",
"preamble",
".",
"append",
"(",
"E2",
".",
"documentation",
"(",
"cls",
".",
"__doc__",
")",
")",
"except",
"AttributeError",
":",
"pass",
"if",
"cls",
".",
"REQUIRED_ATTRIBS",
"is",
"None",
":",
"cls",
".",
"REQUIRED_ATTRIBS",
"=",
"(",
")",
"#bit hacky",
"if",
"cls",
".",
"OPTIONAL_ATTRIBS",
"is",
"None",
":",
"cls",
".",
"OPTIONAL_ATTRIBS",
"=",
"(",
")",
"#bit hacky",
"attribs",
"=",
"[",
"]",
"if",
"cls",
".",
"REQUIRED_ATTRIBS",
"and",
"Attrib",
".",
"ID",
"in",
"cls",
".",
"REQUIRED_ATTRIBS",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"attribute",
"(",
"E",
".",
"data",
"(",
"type",
"=",
"'ID'",
",",
"datatypeLibrary",
"=",
"'http://www.w3.org/2001/XMLSchema-datatypes'",
")",
",",
"name",
"=",
"'id'",
",",
"ns",
"=",
"\"http://www.w3.org/XML/1998/namespace\"",
")",
")",
"elif",
"Attrib",
".",
"ID",
"in",
"cls",
".",
"OPTIONAL_ATTRIBS",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"E",
".",
"data",
"(",
"type",
"=",
"'ID'",
",",
"datatypeLibrary",
"=",
"'http://www.w3.org/2001/XMLSchema-datatypes'",
")",
",",
"name",
"=",
"'id'",
",",
"ns",
"=",
"\"http://www.w3.org/XML/1998/namespace\"",
")",
")",
")",
"if",
"Attrib",
".",
"CLASS",
"in",
"cls",
".",
"REQUIRED_ATTRIBS",
":",
"#Set is a tough one, we can't require it as it may be defined in the declaration: we make it optional and need schematron to resolve this later",
"attribs",
".",
"append",
"(",
"E",
".",
"attribute",
"(",
"E",
".",
"data",
"(",
"type",
"=",
"'string'",
",",
"datatypeLibrary",
"=",
"'http://www.w3.org/2001/XMLSchema-datatypes'",
")",
",",
"name",
"=",
"'class'",
")",
")",
"attribs",
".",
"append",
"(",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"E",
".",
"data",
"(",
"type",
"=",
"'string'",
",",
"datatypeLibrary",
"=",
"'http://www.w3.org/2001/XMLSchema-datatypes'",
")",
",",
"name",
"=",
"'set'",
")",
")",
")",
"elif",
"Attrib",
".",
"CLASS",
"in",
"cls",
".",
"OPTIONAL_ATTRIBS",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"E",
".",
"data",
"(",
"type",
"=",
"'string'",
",",
"datatypeLibrary",
"=",
"'http://www.w3.org/2001/XMLSchema-datatypes'",
")",
",",
"name",
"=",
"'class'",
")",
")",
")",
"attribs",
".",
"append",
"(",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"E",
".",
"data",
"(",
"type",
"=",
"'string'",
",",
"datatypeLibrary",
"=",
"'http://www.w3.org/2001/XMLSchema-datatypes'",
")",
",",
"name",
"=",
"'set'",
")",
")",
")",
"if",
"Attrib",
".",
"ANNOTATOR",
"in",
"cls",
".",
"REQUIRED_ATTRIBS",
"or",
"Attrib",
".",
"ANNOTATOR",
"in",
"cls",
".",
"OPTIONAL_ATTRIBS",
":",
"#Similarly tough",
"attribs",
".",
"append",
"(",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"E",
".",
"data",
"(",
"type",
"=",
"'string'",
",",
"datatypeLibrary",
"=",
"'http://www.w3.org/2001/XMLSchema-datatypes'",
")",
",",
"name",
"=",
"'annotator'",
")",
")",
")",
"attribs",
".",
"append",
"(",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"name",
"=",
"'annotatortype'",
")",
")",
")",
"if",
"Attrib",
".",
"CONFIDENCE",
"in",
"cls",
".",
"REQUIRED_ATTRIBS",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"attribute",
"(",
"E",
".",
"data",
"(",
"type",
"=",
"'double'",
",",
"datatypeLibrary",
"=",
"'http://www.w3.org/2001/XMLSchema-datatypes'",
")",
",",
"name",
"=",
"'confidence'",
")",
")",
"elif",
"Attrib",
".",
"CONFIDENCE",
"in",
"cls",
".",
"OPTIONAL_ATTRIBS",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"E",
".",
"data",
"(",
"type",
"=",
"'double'",
",",
"datatypeLibrary",
"=",
"'http://www.w3.org/2001/XMLSchema-datatypes'",
")",
",",
"name",
"=",
"'confidence'",
")",
")",
")",
"if",
"Attrib",
".",
"N",
"in",
"cls",
".",
"REQUIRED_ATTRIBS",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"attribute",
"(",
"E",
".",
"data",
"(",
"type",
"=",
"'string'",
",",
"datatypeLibrary",
"=",
"'http://www.w3.org/2001/XMLSchema-datatypes'",
")",
",",
"name",
"=",
"'n'",
")",
")",
"elif",
"Attrib",
".",
"N",
"in",
"cls",
".",
"OPTIONAL_ATTRIBS",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"E",
".",
"data",
"(",
"type",
"=",
"'string'",
",",
"datatypeLibrary",
"=",
"'http://www.w3.org/2001/XMLSchema-datatypes'",
")",
",",
"name",
"=",
"'n'",
")",
")",
")",
"if",
"Attrib",
".",
"DATETIME",
"in",
"cls",
".",
"REQUIRED_ATTRIBS",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"attribute",
"(",
"E",
".",
"data",
"(",
"type",
"=",
"'dateTime'",
",",
"datatypeLibrary",
"=",
"'http://www.w3.org/2001/XMLSchema-datatypes'",
")",
",",
"name",
"=",
"'datetime'",
")",
")",
"elif",
"Attrib",
".",
"DATETIME",
"in",
"cls",
".",
"OPTIONAL_ATTRIBS",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"E",
".",
"data",
"(",
"type",
"=",
"'dateTime'",
",",
"datatypeLibrary",
"=",
"'http://www.w3.org/2001/XMLSchema-datatypes'",
")",
",",
"name",
"=",
"'datetime'",
")",
")",
")",
"if",
"Attrib",
".",
"BEGINTIME",
"in",
"cls",
".",
"REQUIRED_ATTRIBS",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"attribute",
"(",
"name",
"=",
"'begintime'",
")",
")",
"elif",
"Attrib",
".",
"BEGINTIME",
"in",
"cls",
".",
"OPTIONAL_ATTRIBS",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"name",
"=",
"'begintime'",
")",
")",
")",
"if",
"Attrib",
".",
"ENDTIME",
"in",
"cls",
".",
"REQUIRED_ATTRIBS",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"attribute",
"(",
"name",
"=",
"'endtime'",
")",
")",
"elif",
"Attrib",
".",
"ENDTIME",
"in",
"cls",
".",
"OPTIONAL_ATTRIBS",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"name",
"=",
"'endtime'",
")",
")",
")",
"if",
"Attrib",
".",
"SRC",
"in",
"cls",
".",
"REQUIRED_ATTRIBS",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"attribute",
"(",
"E",
".",
"data",
"(",
"type",
"=",
"'anyURI'",
",",
"datatypeLibrary",
"=",
"'http://www.w3.org/2001/XMLSchema-datatypes'",
")",
",",
"name",
"=",
"'src'",
")",
")",
"elif",
"Attrib",
".",
"SRC",
"in",
"cls",
".",
"OPTIONAL_ATTRIBS",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"E",
".",
"data",
"(",
"type",
"=",
"'anyURI'",
",",
"datatypeLibrary",
"=",
"'http://www.w3.org/2001/XMLSchema-datatypes'",
")",
",",
"name",
"=",
"'src'",
")",
")",
")",
"if",
"Attrib",
".",
"SPEAKER",
"in",
"cls",
".",
"REQUIRED_ATTRIBS",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"attribute",
"(",
"E",
".",
"data",
"(",
"type",
"=",
"'string'",
",",
"datatypeLibrary",
"=",
"'http://www.w3.org/2001/XMLSchema-datatypes'",
")",
",",
"name",
"=",
"'speaker'",
")",
")",
"elif",
"Attrib",
".",
"SPEAKER",
"in",
"cls",
".",
"OPTIONAL_ATTRIBS",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"E",
".",
"data",
"(",
"type",
"=",
"'string'",
",",
"datatypeLibrary",
"=",
"'http://www.w3.org/2001/XMLSchema-datatypes'",
")",
",",
"name",
"=",
"'speaker'",
")",
")",
")",
"if",
"Attrib",
".",
"TEXTCLASS",
"in",
"cls",
".",
"REQUIRED_ATTRIBS",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"attribute",
"(",
"name",
"=",
"'textclass'",
")",
")",
"elif",
"Attrib",
".",
"TEXTCLASS",
"in",
"cls",
".",
"OPTIONAL_ATTRIBS",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"name",
"=",
"'textclass'",
")",
")",
")",
"if",
"Attrib",
".",
"METADATA",
"in",
"cls",
".",
"REQUIRED_ATTRIBS",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"attribute",
"(",
"name",
"=",
"'metadata'",
")",
")",
"elif",
"Attrib",
".",
"METADATA",
"in",
"cls",
".",
"OPTIONAL_ATTRIBS",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"name",
"=",
"'metadata'",
")",
")",
")",
"if",
"cls",
".",
"XLINK",
":",
"attribs",
"+=",
"[",
"#loose interpretation of specs, not checking whether xlink combinations are valid",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"name",
"=",
"'href'",
",",
"ns",
"=",
"\"http://www.w3.org/1999/xlink\"",
")",
",",
"E",
".",
"attribute",
"(",
"name",
"=",
"'type'",
",",
"ns",
"=",
"\"http://www.w3.org/1999/xlink\"",
")",
")",
",",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"name",
"=",
"'role'",
",",
"ns",
"=",
"\"http://www.w3.org/1999/xlink\"",
")",
")",
",",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"name",
"=",
"'title'",
",",
"ns",
"=",
"\"http://www.w3.org/1999/xlink\"",
")",
")",
",",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"name",
"=",
"'label'",
",",
"ns",
"=",
"\"http://www.w3.org/1999/xlink\"",
")",
")",
",",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"name",
"=",
"'show'",
",",
"ns",
"=",
"\"http://www.w3.org/1999/xlink\"",
")",
")",
",",
"]",
"attribs",
".",
"append",
"(",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"name",
"=",
"'auth'",
")",
")",
")",
"if",
"extraattribs",
":",
"for",
"e",
"in",
"extraattribs",
":",
"attribs",
".",
"append",
"(",
"e",
")",
"#s",
"attribs",
".",
"append",
"(",
"E",
".",
"ref",
"(",
"name",
"=",
"\"allow_foreign_attributes\"",
")",
")",
"elements",
"=",
"[",
"]",
"#(including attributes)",
"if",
"cls",
".",
"TEXTCONTAINER",
"or",
"cls",
".",
"PHONCONTAINER",
":",
"elements",
".",
"append",
"(",
"E",
".",
"text",
"(",
")",
")",
"#We actually want to require non-empty text (E.text() is not sufficient)",
"#but this is not solved yet, see https://github.com/proycon/folia/issues/19",
"#elements.append( E.data(E.param(r\".+\",name=\"pattern\"),type='string'))",
"#elements.append( E.data(E.param(r\"(.|\\n|\\r)*\\S+(.|\\n|\\r)*\",name=\"pattern\"),type='string'))",
"done",
"=",
"{",
"}",
"if",
"includechildren",
"and",
"cls",
".",
"ACCEPTED_DATA",
":",
"#pylint: disable=too-many-nested-blocks",
"for",
"c",
"in",
"cls",
".",
"ACCEPTED_DATA",
":",
"if",
"c",
".",
"__name__",
"[",
":",
"8",
"]",
"==",
"'Abstract'",
"and",
"inspect",
".",
"isclass",
"(",
"c",
")",
":",
"for",
"c2",
"in",
"globals",
"(",
")",
".",
"values",
"(",
")",
":",
"try",
":",
"if",
"inspect",
".",
"isclass",
"(",
"c2",
")",
"and",
"issubclass",
"(",
"c2",
",",
"c",
")",
":",
"try",
":",
"if",
"c2",
".",
"XMLTAG",
"and",
"c2",
".",
"XMLTAG",
"not",
"in",
"done",
":",
"if",
"c2",
".",
"OCCURRENCES",
"==",
"1",
":",
"elements",
".",
"append",
"(",
"E",
".",
"optional",
"(",
"E",
".",
"ref",
"(",
"name",
"=",
"c2",
".",
"XMLTAG",
")",
")",
")",
"else",
":",
"elements",
".",
"append",
"(",
"E",
".",
"zeroOrMore",
"(",
"E",
".",
"ref",
"(",
"name",
"=",
"c2",
".",
"XMLTAG",
")",
")",
")",
"if",
"c2",
".",
"XMLTAG",
"==",
"'item'",
":",
"#nasty hack for backward compatibility with deprecated listitem element",
"elements",
".",
"append",
"(",
"E",
".",
"zeroOrMore",
"(",
"E",
".",
"ref",
"(",
"name",
"=",
"'listitem'",
")",
")",
")",
"done",
"[",
"c2",
".",
"XMLTAG",
"]",
"=",
"True",
"except",
"AttributeError",
":",
"continue",
"except",
"TypeError",
":",
"pass",
"elif",
"issubclass",
"(",
"c",
",",
"Feature",
")",
"and",
"c",
".",
"SUBSET",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"optional",
"(",
"E",
".",
"attribute",
"(",
"name",
"=",
"c",
".",
"SUBSET",
")",
")",
")",
"#features as attributes",
"else",
":",
"try",
":",
"if",
"c",
".",
"XMLTAG",
"and",
"c",
".",
"XMLTAG",
"not",
"in",
"done",
":",
"if",
"cls",
".",
"REQUIRED_DATA",
"and",
"c",
"in",
"cls",
".",
"REQUIRED_DATA",
":",
"if",
"c",
".",
"OCCURRENCES",
"==",
"1",
":",
"elements",
".",
"append",
"(",
"E",
".",
"ref",
"(",
"name",
"=",
"c",
".",
"XMLTAG",
")",
")",
"else",
":",
"elements",
".",
"append",
"(",
"E",
".",
"oneOrMore",
"(",
"E",
".",
"ref",
"(",
"name",
"=",
"c",
".",
"XMLTAG",
")",
")",
")",
"elif",
"c",
".",
"OCCURRENCES",
"==",
"1",
":",
"elements",
".",
"append",
"(",
"E",
".",
"optional",
"(",
"E",
".",
"ref",
"(",
"name",
"=",
"c",
".",
"XMLTAG",
")",
")",
")",
"else",
":",
"elements",
".",
"append",
"(",
"E",
".",
"zeroOrMore",
"(",
"E",
".",
"ref",
"(",
"name",
"=",
"c",
".",
"XMLTAG",
")",
")",
")",
"if",
"c",
".",
"XMLTAG",
"==",
"'item'",
":",
"#nasty hack for backward compatibility with deprecated listitem element",
"elements",
".",
"append",
"(",
"E",
".",
"zeroOrMore",
"(",
"E",
".",
"ref",
"(",
"name",
"=",
"'listitem'",
")",
")",
")",
"done",
"[",
"c",
".",
"XMLTAG",
"]",
"=",
"True",
"except",
"AttributeError",
":",
"continue",
"if",
"extraelements",
":",
"for",
"e",
"in",
"extraelements",
":",
"elements",
".",
"append",
"(",
"e",
")",
"if",
"elements",
":",
"if",
"len",
"(",
"elements",
")",
">",
"1",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"interleave",
"(",
"*",
"elements",
")",
")",
"else",
":",
"attribs",
".",
"append",
"(",
"*",
"elements",
")",
"if",
"not",
"attribs",
":",
"attribs",
".",
"append",
"(",
"E",
".",
"empty",
"(",
")",
")",
"if",
"cls",
".",
"XMLTAG",
"in",
"(",
"'desc'",
",",
"'comment'",
")",
":",
"return",
"E",
".",
"define",
"(",
"E",
".",
"element",
"(",
"E",
".",
"text",
"(",
")",
",",
"*",
"(",
"preamble",
"+",
"attribs",
")",
",",
"*",
"*",
"{",
"'name'",
":",
"cls",
".",
"XMLTAG",
"}",
")",
",",
"name",
"=",
"cls",
".",
"XMLTAG",
",",
"ns",
"=",
"NSFOLIA",
")",
"else",
":",
"return",
"E",
".",
"define",
"(",
"E",
".",
"element",
"(",
"*",
"(",
"preamble",
"+",
"attribs",
")",
",",
"*",
"*",
"{",
"'name'",
":",
"cls",
".",
"XMLTAG",
"}",
")",
",",
"name",
"=",
"cls",
".",
"XMLTAG",
",",
"ns",
"=",
"NSFOLIA",
")"
] | Returns a RelaxNG definition for this element (as an XML element (lxml.etree) rather than a string) | [
"Returns",
"a",
"RelaxNG",
"definition",
"for",
"this",
"element",
"(",
"as",
"an",
"XML",
"element",
"(",
"lxml",
".",
"etree",
")",
"rather",
"than",
"a",
"string",
")"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L2424-L2579 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.parsexml | def parsexml(Class, node, doc, **kwargs): #pylint: disable=bad-classmethod-argument
"""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.
"""
assert issubclass(Class, AbstractElement)
if doc.preparsexmlcallback:
result = doc.preparsexmlcallback(node)
if not result:
return None
if isinstance(result, AbstractElement):
return result
dcoi = node.tag.startswith('{' + NSDCOI + '}')
args = []
if not kwargs: kwargs = {}
text = None #for dcoi support
if (Class.TEXTCONTAINER or Class.PHONCONTAINER) and node.text:
args.append(node.text)
for subnode in node: #pylint: disable=too-many-nested-blocks
#don't trip over comments
if isinstance(subnode, ElementTree._Comment): #pylint: disable=protected-access
if (Class.TEXTCONTAINER or Class.PHONCONTAINER) and subnode.tail:
args.append(subnode.tail)
else:
if subnode.tag.startswith('{' + NSFOLIA + '}'):
if doc.debug >= 1: print("[PyNLPl FoLiA DEBUG] Processing subnode " + subnode.tag[nslen:],file=stderr)
try:
e = doc.parsexml(subnode, Class)
except ParseError as e:
raise #just re-raise deepest parseError
except Exception as e:
#Python 3 will preserve full original traceback, Python 2 does not, original cause is explicitly passed to ParseError anyway:
raise ParseError("FoLiA exception in handling of <" + subnode.tag[len(NSFOLIA)+2:] + "> @ line " + str(subnode.sourceline) + ": [" + e.__class__.__name__ + "] " + str(e), cause=e)
if e is not None:
args.append(e)
if (Class.TEXTCONTAINER or Class.PHONCONTAINER) and subnode.tail:
args.append(subnode.tail)
elif subnode.tag.startswith('{' + NSDCOI + '}'):
#Dcoi support
if Class is Text and subnode.tag[nslendcoi:] == 'body':
for subsubnode in subnode:
if doc.debug >= 1: print("[PyNLPl FoLiA DEBUG] Processing DCOI subnode " + subnode.tag[nslendcoi:],file=stderr)
e = doc.parsexml(subsubnode, Class)
if e is not None:
args.append(e)
else:
if doc.debug >= 1: print( "[PyNLPl FoLiA DEBUG] Processing DCOI subnode " + subnode.tag[nslendcoi:],file=stderr)
e = doc.parsexml(subnode, Class)
if e is not None:
args.append(e)
elif doc.debug >= 1:
print("[PyNLPl FoLiA DEBUG] Ignoring subnode outside of FoLiA namespace: " + subnode.tag,file=stderr)
if dcoi:
dcoipos = dcoilemma = dcoicorrection = dcoicorrectionoriginal = None
for key, value in node.attrib.items():
if key[0] == '{' or key =='XMLid':
if key == '{http://www.w3.org/XML/1998/namespace}id' or key == 'XMLid':
key = 'id'
elif key.startswith( '{' + NSFOLIA + '}'):
key = key[nslen:]
if key == 'id':
#ID in FoLiA namespace is always a reference, passed in kwargs as follows:
key = 'idref'
elif Class.XLINK and key.startswith('{http://www.w3.org/1999/xlink}'):
key = key[30:]
if key != 'href':
key = 'xlink' + key #xlinktype, xlinkrole, xlinklabel, xlinkshow, etc..
elif key.startswith('{' + NSDCOI + '}'):
key = key[nslendcoi:]
#D-Coi support:
if dcoi:
if Class is Word and key == 'pos':
dcoipos = value
continue
elif Class is Word and key == 'lemma':
dcoilemma = value
continue
elif Class is Word and key == 'correction':
dcoicorrection = value #class
continue
elif Class is Word and key == 'original':
dcoicorrectionoriginal = value
continue
elif Class is Gap and key == 'reason':
key = 'class'
elif Class is Gap and key == 'hand':
key = 'annotator'
elif Class is Division and key == 'type':
key = 'cls'
kwargs[key] = value
#D-Coi support:
if dcoi and TextContent in Class.ACCEPTED_DATA and node.text:
text = node.text.strip()
kwargs['text'] = text
if not AnnotationType.TOKEN in doc.annotationdefaults:
doc.declare(AnnotationType.TOKEN, set='http://ilk.uvt.nl/folia/sets/ilktok.foliaset')
if doc.debug >= 1: print("[PyNLPl FoLiA DEBUG] Found " + node.tag[nslen:],file=stderr)
instance = Class(doc, *args, **kwargs)
#if id:
# if doc.debug >= 1: print >>stderr, "[PyNLPl FoLiA DEBUG] Adding to index: " + id
# doc.index[id] = instance
if dcoi:
if dcoipos:
if not AnnotationType.POS in doc.annotationdefaults:
doc.declare(AnnotationType.POS, set='http://ilk.uvt.nl/folia/sets/cgn-legacy.foliaset')
instance.append( PosAnnotation(doc, cls=dcoipos) )
if dcoilemma:
if not AnnotationType.LEMMA in doc.annotationdefaults:
doc.declare(AnnotationType.LEMMA, set='http://ilk.uvt.nl/folia/sets/mblem-nl.foliaset')
instance.append( LemmaAnnotation(doc, cls=dcoilemma) )
if dcoicorrection and dcoicorrectionoriginal and text:
if not AnnotationType.CORRECTION in doc.annotationdefaults:
doc.declare(AnnotationType.CORRECTION, set='http://ilk.uvt.nl/folia/sets/dcoi-corrections.foliaset')
instance.correct(generate_id_in=instance, cls=dcoicorrection, original=dcoicorrectionoriginal, new=text)
if doc.parsexmlcallback:
result = doc.parsexmlcallback(instance)
if not result:
return None
if isinstance(result, AbstractElement):
return result
return instance | python | def parsexml(Class, node, doc, **kwargs): #pylint: disable=bad-classmethod-argument
"""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.
"""
assert issubclass(Class, AbstractElement)
if doc.preparsexmlcallback:
result = doc.preparsexmlcallback(node)
if not result:
return None
if isinstance(result, AbstractElement):
return result
dcoi = node.tag.startswith('{' + NSDCOI + '}')
args = []
if not kwargs: kwargs = {}
text = None #for dcoi support
if (Class.TEXTCONTAINER or Class.PHONCONTAINER) and node.text:
args.append(node.text)
for subnode in node: #pylint: disable=too-many-nested-blocks
#don't trip over comments
if isinstance(subnode, ElementTree._Comment): #pylint: disable=protected-access
if (Class.TEXTCONTAINER or Class.PHONCONTAINER) and subnode.tail:
args.append(subnode.tail)
else:
if subnode.tag.startswith('{' + NSFOLIA + '}'):
if doc.debug >= 1: print("[PyNLPl FoLiA DEBUG] Processing subnode " + subnode.tag[nslen:],file=stderr)
try:
e = doc.parsexml(subnode, Class)
except ParseError as e:
raise #just re-raise deepest parseError
except Exception as e:
#Python 3 will preserve full original traceback, Python 2 does not, original cause is explicitly passed to ParseError anyway:
raise ParseError("FoLiA exception in handling of <" + subnode.tag[len(NSFOLIA)+2:] + "> @ line " + str(subnode.sourceline) + ": [" + e.__class__.__name__ + "] " + str(e), cause=e)
if e is not None:
args.append(e)
if (Class.TEXTCONTAINER or Class.PHONCONTAINER) and subnode.tail:
args.append(subnode.tail)
elif subnode.tag.startswith('{' + NSDCOI + '}'):
#Dcoi support
if Class is Text and subnode.tag[nslendcoi:] == 'body':
for subsubnode in subnode:
if doc.debug >= 1: print("[PyNLPl FoLiA DEBUG] Processing DCOI subnode " + subnode.tag[nslendcoi:],file=stderr)
e = doc.parsexml(subsubnode, Class)
if e is not None:
args.append(e)
else:
if doc.debug >= 1: print( "[PyNLPl FoLiA DEBUG] Processing DCOI subnode " + subnode.tag[nslendcoi:],file=stderr)
e = doc.parsexml(subnode, Class)
if e is not None:
args.append(e)
elif doc.debug >= 1:
print("[PyNLPl FoLiA DEBUG] Ignoring subnode outside of FoLiA namespace: " + subnode.tag,file=stderr)
if dcoi:
dcoipos = dcoilemma = dcoicorrection = dcoicorrectionoriginal = None
for key, value in node.attrib.items():
if key[0] == '{' or key =='XMLid':
if key == '{http://www.w3.org/XML/1998/namespace}id' or key == 'XMLid':
key = 'id'
elif key.startswith( '{' + NSFOLIA + '}'):
key = key[nslen:]
if key == 'id':
#ID in FoLiA namespace is always a reference, passed in kwargs as follows:
key = 'idref'
elif Class.XLINK and key.startswith('{http://www.w3.org/1999/xlink}'):
key = key[30:]
if key != 'href':
key = 'xlink' + key #xlinktype, xlinkrole, xlinklabel, xlinkshow, etc..
elif key.startswith('{' + NSDCOI + '}'):
key = key[nslendcoi:]
#D-Coi support:
if dcoi:
if Class is Word and key == 'pos':
dcoipos = value
continue
elif Class is Word and key == 'lemma':
dcoilemma = value
continue
elif Class is Word and key == 'correction':
dcoicorrection = value #class
continue
elif Class is Word and key == 'original':
dcoicorrectionoriginal = value
continue
elif Class is Gap and key == 'reason':
key = 'class'
elif Class is Gap and key == 'hand':
key = 'annotator'
elif Class is Division and key == 'type':
key = 'cls'
kwargs[key] = value
#D-Coi support:
if dcoi and TextContent in Class.ACCEPTED_DATA and node.text:
text = node.text.strip()
kwargs['text'] = text
if not AnnotationType.TOKEN in doc.annotationdefaults:
doc.declare(AnnotationType.TOKEN, set='http://ilk.uvt.nl/folia/sets/ilktok.foliaset')
if doc.debug >= 1: print("[PyNLPl FoLiA DEBUG] Found " + node.tag[nslen:],file=stderr)
instance = Class(doc, *args, **kwargs)
#if id:
# if doc.debug >= 1: print >>stderr, "[PyNLPl FoLiA DEBUG] Adding to index: " + id
# doc.index[id] = instance
if dcoi:
if dcoipos:
if not AnnotationType.POS in doc.annotationdefaults:
doc.declare(AnnotationType.POS, set='http://ilk.uvt.nl/folia/sets/cgn-legacy.foliaset')
instance.append( PosAnnotation(doc, cls=dcoipos) )
if dcoilemma:
if not AnnotationType.LEMMA in doc.annotationdefaults:
doc.declare(AnnotationType.LEMMA, set='http://ilk.uvt.nl/folia/sets/mblem-nl.foliaset')
instance.append( LemmaAnnotation(doc, cls=dcoilemma) )
if dcoicorrection and dcoicorrectionoriginal and text:
if not AnnotationType.CORRECTION in doc.annotationdefaults:
doc.declare(AnnotationType.CORRECTION, set='http://ilk.uvt.nl/folia/sets/dcoi-corrections.foliaset')
instance.correct(generate_id_in=instance, cls=dcoicorrection, original=dcoicorrectionoriginal, new=text)
if doc.parsexmlcallback:
result = doc.parsexmlcallback(instance)
if not result:
return None
if isinstance(result, AbstractElement):
return result
return instance | [
"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",
",",
"AbstractElement",
")",
":",
"return",
"result",
"dcoi",
"=",
"node",
".",
"tag",
".",
"startswith",
"(",
"'{'",
"+",
"NSDCOI",
"+",
"'}'",
")",
"args",
"=",
"[",
"]",
"if",
"not",
"kwargs",
":",
"kwargs",
"=",
"{",
"}",
"text",
"=",
"None",
"#for dcoi support",
"if",
"(",
"Class",
".",
"TEXTCONTAINER",
"or",
"Class",
".",
"PHONCONTAINER",
")",
"and",
"node",
".",
"text",
":",
"args",
".",
"append",
"(",
"node",
".",
"text",
")",
"for",
"subnode",
"in",
"node",
":",
"#pylint: disable=too-many-nested-blocks",
"#don't trip over comments",
"if",
"isinstance",
"(",
"subnode",
",",
"ElementTree",
".",
"_Comment",
")",
":",
"#pylint: disable=protected-access",
"if",
"(",
"Class",
".",
"TEXTCONTAINER",
"or",
"Class",
".",
"PHONCONTAINER",
")",
"and",
"subnode",
".",
"tail",
":",
"args",
".",
"append",
"(",
"subnode",
".",
"tail",
")",
"else",
":",
"if",
"subnode",
".",
"tag",
".",
"startswith",
"(",
"'{'",
"+",
"NSFOLIA",
"+",
"'}'",
")",
":",
"if",
"doc",
".",
"debug",
">=",
"1",
":",
"print",
"(",
"\"[PyNLPl FoLiA DEBUG] Processing subnode \"",
"+",
"subnode",
".",
"tag",
"[",
"nslen",
":",
"]",
",",
"file",
"=",
"stderr",
")",
"try",
":",
"e",
"=",
"doc",
".",
"parsexml",
"(",
"subnode",
",",
"Class",
")",
"except",
"ParseError",
"as",
"e",
":",
"raise",
"#just re-raise deepest parseError",
"except",
"Exception",
"as",
"e",
":",
"#Python 3 will preserve full original traceback, Python 2 does not, original cause is explicitly passed to ParseError anyway:",
"raise",
"ParseError",
"(",
"\"FoLiA exception in handling of <\"",
"+",
"subnode",
".",
"tag",
"[",
"len",
"(",
"NSFOLIA",
")",
"+",
"2",
":",
"]",
"+",
"\"> @ line \"",
"+",
"str",
"(",
"subnode",
".",
"sourceline",
")",
"+",
"\": [\"",
"+",
"e",
".",
"__class__",
".",
"__name__",
"+",
"\"] \"",
"+",
"str",
"(",
"e",
")",
",",
"cause",
"=",
"e",
")",
"if",
"e",
"is",
"not",
"None",
":",
"args",
".",
"append",
"(",
"e",
")",
"if",
"(",
"Class",
".",
"TEXTCONTAINER",
"or",
"Class",
".",
"PHONCONTAINER",
")",
"and",
"subnode",
".",
"tail",
":",
"args",
".",
"append",
"(",
"subnode",
".",
"tail",
")",
"elif",
"subnode",
".",
"tag",
".",
"startswith",
"(",
"'{'",
"+",
"NSDCOI",
"+",
"'}'",
")",
":",
"#Dcoi support",
"if",
"Class",
"is",
"Text",
"and",
"subnode",
".",
"tag",
"[",
"nslendcoi",
":",
"]",
"==",
"'body'",
":",
"for",
"subsubnode",
"in",
"subnode",
":",
"if",
"doc",
".",
"debug",
">=",
"1",
":",
"print",
"(",
"\"[PyNLPl FoLiA DEBUG] Processing DCOI subnode \"",
"+",
"subnode",
".",
"tag",
"[",
"nslendcoi",
":",
"]",
",",
"file",
"=",
"stderr",
")",
"e",
"=",
"doc",
".",
"parsexml",
"(",
"subsubnode",
",",
"Class",
")",
"if",
"e",
"is",
"not",
"None",
":",
"args",
".",
"append",
"(",
"e",
")",
"else",
":",
"if",
"doc",
".",
"debug",
">=",
"1",
":",
"print",
"(",
"\"[PyNLPl FoLiA DEBUG] Processing DCOI subnode \"",
"+",
"subnode",
".",
"tag",
"[",
"nslendcoi",
":",
"]",
",",
"file",
"=",
"stderr",
")",
"e",
"=",
"doc",
".",
"parsexml",
"(",
"subnode",
",",
"Class",
")",
"if",
"e",
"is",
"not",
"None",
":",
"args",
".",
"append",
"(",
"e",
")",
"elif",
"doc",
".",
"debug",
">=",
"1",
":",
"print",
"(",
"\"[PyNLPl FoLiA DEBUG] Ignoring subnode outside of FoLiA namespace: \"",
"+",
"subnode",
".",
"tag",
",",
"file",
"=",
"stderr",
")",
"if",
"dcoi",
":",
"dcoipos",
"=",
"dcoilemma",
"=",
"dcoicorrection",
"=",
"dcoicorrectionoriginal",
"=",
"None",
"for",
"key",
",",
"value",
"in",
"node",
".",
"attrib",
".",
"items",
"(",
")",
":",
"if",
"key",
"[",
"0",
"]",
"==",
"'{'",
"or",
"key",
"==",
"'XMLid'",
":",
"if",
"key",
"==",
"'{http://www.w3.org/XML/1998/namespace}id'",
"or",
"key",
"==",
"'XMLid'",
":",
"key",
"=",
"'id'",
"elif",
"key",
".",
"startswith",
"(",
"'{'",
"+",
"NSFOLIA",
"+",
"'}'",
")",
":",
"key",
"=",
"key",
"[",
"nslen",
":",
"]",
"if",
"key",
"==",
"'id'",
":",
"#ID in FoLiA namespace is always a reference, passed in kwargs as follows:",
"key",
"=",
"'idref'",
"elif",
"Class",
".",
"XLINK",
"and",
"key",
".",
"startswith",
"(",
"'{http://www.w3.org/1999/xlink}'",
")",
":",
"key",
"=",
"key",
"[",
"30",
":",
"]",
"if",
"key",
"!=",
"'href'",
":",
"key",
"=",
"'xlink'",
"+",
"key",
"#xlinktype, xlinkrole, xlinklabel, xlinkshow, etc..",
"elif",
"key",
".",
"startswith",
"(",
"'{'",
"+",
"NSDCOI",
"+",
"'}'",
")",
":",
"key",
"=",
"key",
"[",
"nslendcoi",
":",
"]",
"#D-Coi support:",
"if",
"dcoi",
":",
"if",
"Class",
"is",
"Word",
"and",
"key",
"==",
"'pos'",
":",
"dcoipos",
"=",
"value",
"continue",
"elif",
"Class",
"is",
"Word",
"and",
"key",
"==",
"'lemma'",
":",
"dcoilemma",
"=",
"value",
"continue",
"elif",
"Class",
"is",
"Word",
"and",
"key",
"==",
"'correction'",
":",
"dcoicorrection",
"=",
"value",
"#class",
"continue",
"elif",
"Class",
"is",
"Word",
"and",
"key",
"==",
"'original'",
":",
"dcoicorrectionoriginal",
"=",
"value",
"continue",
"elif",
"Class",
"is",
"Gap",
"and",
"key",
"==",
"'reason'",
":",
"key",
"=",
"'class'",
"elif",
"Class",
"is",
"Gap",
"and",
"key",
"==",
"'hand'",
":",
"key",
"=",
"'annotator'",
"elif",
"Class",
"is",
"Division",
"and",
"key",
"==",
"'type'",
":",
"key",
"=",
"'cls'",
"kwargs",
"[",
"key",
"]",
"=",
"value",
"#D-Coi support:",
"if",
"dcoi",
"and",
"TextContent",
"in",
"Class",
".",
"ACCEPTED_DATA",
"and",
"node",
".",
"text",
":",
"text",
"=",
"node",
".",
"text",
".",
"strip",
"(",
")",
"kwargs",
"[",
"'text'",
"]",
"=",
"text",
"if",
"not",
"AnnotationType",
".",
"TOKEN",
"in",
"doc",
".",
"annotationdefaults",
":",
"doc",
".",
"declare",
"(",
"AnnotationType",
".",
"TOKEN",
",",
"set",
"=",
"'http://ilk.uvt.nl/folia/sets/ilktok.foliaset'",
")",
"if",
"doc",
".",
"debug",
">=",
"1",
":",
"print",
"(",
"\"[PyNLPl FoLiA DEBUG] Found \"",
"+",
"node",
".",
"tag",
"[",
"nslen",
":",
"]",
",",
"file",
"=",
"stderr",
")",
"instance",
"=",
"Class",
"(",
"doc",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"#if id:",
"# if doc.debug >= 1: print >>stderr, \"[PyNLPl FoLiA DEBUG] Adding to index: \" + id",
"# doc.index[id] = instance",
"if",
"dcoi",
":",
"if",
"dcoipos",
":",
"if",
"not",
"AnnotationType",
".",
"POS",
"in",
"doc",
".",
"annotationdefaults",
":",
"doc",
".",
"declare",
"(",
"AnnotationType",
".",
"POS",
",",
"set",
"=",
"'http://ilk.uvt.nl/folia/sets/cgn-legacy.foliaset'",
")",
"instance",
".",
"append",
"(",
"PosAnnotation",
"(",
"doc",
",",
"cls",
"=",
"dcoipos",
")",
")",
"if",
"dcoilemma",
":",
"if",
"not",
"AnnotationType",
".",
"LEMMA",
"in",
"doc",
".",
"annotationdefaults",
":",
"doc",
".",
"declare",
"(",
"AnnotationType",
".",
"LEMMA",
",",
"set",
"=",
"'http://ilk.uvt.nl/folia/sets/mblem-nl.foliaset'",
")",
"instance",
".",
"append",
"(",
"LemmaAnnotation",
"(",
"doc",
",",
"cls",
"=",
"dcoilemma",
")",
")",
"if",
"dcoicorrection",
"and",
"dcoicorrectionoriginal",
"and",
"text",
":",
"if",
"not",
"AnnotationType",
".",
"CORRECTION",
"in",
"doc",
".",
"annotationdefaults",
":",
"doc",
".",
"declare",
"(",
"AnnotationType",
".",
"CORRECTION",
",",
"set",
"=",
"'http://ilk.uvt.nl/folia/sets/dcoi-corrections.foliaset'",
")",
"instance",
".",
"correct",
"(",
"generate_id_in",
"=",
"instance",
",",
"cls",
"=",
"dcoicorrection",
",",
"original",
"=",
"dcoicorrectionoriginal",
",",
"new",
"=",
"text",
")",
"if",
"doc",
".",
"parsexmlcallback",
":",
"result",
"=",
"doc",
".",
"parsexmlcallback",
"(",
"instance",
")",
"if",
"not",
"result",
":",
"return",
"None",
"if",
"isinstance",
"(",
"result",
",",
"AbstractElement",
")",
":",
"return",
"result",
"return",
"instance"
] | 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. | [
"Internal",
"class",
"method",
"used",
"for",
"turning",
"an",
"XML",
"element",
"into",
"an",
"instance",
"of",
"the",
"Class",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L2582-L2724 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.remove | def remove(self, child):
"""Removes the child element"""
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] | python | def remove(self, child):
"""Removes the child element"""
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",
")",
":",
"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",
"]"
] | Removes the child element | [
"Removes",
"the",
"child",
"element"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L2729-L2738 |
proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.incorrection | 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"""
e = self.parent
while e:
if isinstance(e, Correction):
return e
if isinstance(e, AbstractStructureElement):
break
e = e.parent
return None | python | 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"""
e = self.parent
while e:
if isinstance(e, Correction):
return e
if isinstance(e, AbstractStructureElement):
break
e = e.parent
return None | [
"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 | [
"Is",
"this",
"element",
"part",
"of",
"a",
"correction?",
"If",
"it",
"is",
"it",
"returns",
"the",
"Correction",
"element",
"(",
"evaluating",
"to",
"True",
")",
"otherwise",
"it",
"returns",
"None"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L2740-L2750 |
End of preview. Expand
in Dataset Viewer.
code-search-net/code_search_net , already loaded and converted to paraquet so you dont have to enable remote execution to use it .
- Downloads last month
- 40