drepr.writers.turtle_writer#

Classes

MyLiteral(lexical_or_value[, lang, ...])

TurtleWriter(prefixes[, normalize_uri])

class MyLiteral(lexical_or_value: Any, lang: Optional[str] = None, datatype: Optional[str] = None, normalize: Optional[bool] = None)[source]#

Bases: Literal

Parameters:
  • lexical_or_value (Any) –

  • lang (Optional[str]) –

  • datatype (Optional[str]) –

  • normalize (Optional[bool]) –

n3(namespace_manager: Optional[NamespaceManager] = None)[source]#

Returns a representation in the N3 format.

```python >>> Literal(“foo”).n3() ‘“foo”’

```

Strings with newlines or triple-quotes:

```python >>> Literal(“foonbar”).n3() ‘”””foonbar”””’ >>> Literal(”’’'”).n3() ‘”'''”’ >>> Literal(‘”””’).n3() ‘”\”\”\””’

```

Language:

```python >>> Literal(“hello”, lang=”en”).n3() ‘“hello”@en’

```

Datatypes:

```python >>> Literal(1).n3() ‘“1”^^<http://www.w3.org/2001/XMLSchema#integer>’ >>> Literal(1.0).n3() ‘“1.0”^^<http://www.w3.org/2001/XMLSchema#double>’ >>> Literal(True).n3() ‘“true”^^<http://www.w3.org/2001/XMLSchema#boolean>’

```

Datatype and language isn’t allowed (datatype takes precedence):

```python >>> Literal(1, lang=”en”).n3() ‘“1”^^<http://www.w3.org/2001/XMLSchema#integer>’

```

Custom datatype:

```python >>> footype = URIRef(”http://example.org/ns#foo”) >>> Literal(“1”, datatype=footype).n3() ‘“1”^^<http://example.org/ns#foo>’

```

Passing a namespace-manager will use it to abbreviate datatype URIs:

```python >>> from rdflib import Graph >>> Literal(1).n3(Graph().namespace_manager) ‘“1”^^xsd:integer’

```

Parameters:

namespace_manager (Optional[NamespaceManager]) –

capitalize()#

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold()#

Return a version of the string suitable for caseless comparisons.

center(width, fillchar=' ', /)#

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

count(sub[, start[, end]]) int#

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

property datatype: Optional[URIRef]#
encode(encoding='utf-8', errors='strict')#

Encode the string using the codec registered for encoding.

encoding

The encoding in which to encode the string.

errors

The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

endswith(suffix[, start[, end]]) bool#

Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

eq(other: Any) bool#

Compare the value of this literal with something else.

This comparison can be done in two ways:

  1. With the value of another literal - comparisons are then done in literal “value space”

    according to the rules of XSD subtype-substitution/type-promotion

  2. With a Python object: * string objects can be compared with plain-literals or those with datatype xsd:string * bool objects with xsd:boolean * int, long or float with numeric xsd types * date, time, datetime objects with xsd:date, xsd:time, xsd:datetime

Any other operations returns NotImplemented.

Parameters:

other (Any) –

Return type:

bool

expandtabs(tabsize=8)#

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find(sub[, start[, end]]) int#

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

format(*args, **kwargs) str#

Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).

format_map(mapping) str#

Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).

property ill_typed: Optional[bool]#

For recognized datatype IRIs, this value will be True if the literal is ill formed, otherwise it will be False. Literal.value (i.e. the literal value) should always be defined if this property is False, but should not be considered reliable if this property is True.

If the literal’s datatype is None or not in the set of recognized datatype IRIs this value will be None.

index(sub[, start[, end]]) int#

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

isalnum()#

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isalpha()#

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isascii()#

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

isdecimal()#

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit()#

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isidentifier()#

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

islower()#

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isnumeric()#

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isprintable()#

Return True if the string is printable, False otherwise.

A string is printable if all of its characters are considered printable in repr() or if it is empty.

isspace()#

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

istitle()#

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isupper()#

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

join(iterable, /)#

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

property language: Optional[str]#
ljust(width, fillchar=' ', /)#

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower()#

Return a copy of the string converted to lowercase.

lstrip(chars=None, /)#

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

static maketrans()#

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

neq(other: Any) bool#

A “semantic”/interpreted not equal function, by default, same as __ne__

Parameters:

other (Any) –

Return type:

bool

normalize() Literal#

Returns a new literal with a normalised lexical representation of this literal

```python >>> from rdflib import XSD >>> Literal(“01”, datatype=XSD.integer, normalize=False).normalize() rdflib.term.Literal(‘1’, datatype=rdflib.term.URIRef(’http://www.w3.org/2001/XMLSchema#integer’))

```

Illegal lexical forms for the datatype given are simply passed on

```python >>> Literal(“a”, datatype=XSD.integer, normalize=False) rdflib.term.Literal(‘a’, datatype=rdflib.term.URIRef(’http://www.w3.org/2001/XMLSchema#integer’))

```

Return type:

Literal

partition(sep, /)#

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

removeprefix(prefix, /)#

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.

removesuffix(suffix, /)#

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.

replace(old, new, count=- 1, /)#

Return a copy with all occurrences of substring old replaced by new.

count

Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

rfind(sub[, start[, end]]) int#

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

rindex(sub[, start[, end]]) int#

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

rjust(width, fillchar=' ', /)#

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rpartition(sep, /)#

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

rsplit(sep=None, maxsplit=- 1)#

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the end of the string and works to the front.

rstrip(chars=None, /)#

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

split(sep=None, maxsplit=- 1)#

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the front of the string and works to the end.

Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.

splitlines(keepends=False)#

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

startswith(prefix[, start[, end]]) bool#

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

Parameters:

prefix (str) –

Return type:

bool

strip(chars=None, /)#

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase()#

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title()#

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

toPython() Any#

Returns an appropriate python datatype derived from this RDF Literal

Return type:

Any

translate(table, /)#

Replace each character in the string using the given translation table.

table

Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper()#

Return a copy of the string converted to uppercase.

property value: Any#
zfill(width, /)#

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

class TurtleWriter(prefixes: dict[str, str], normalize_uri: Optional[bool] = None)[source]#

Bases: StreamClassWriter

Parameters:
has_written_record(subject: str | tuple | int | bool) bool[source]#

Test if a record of a given subject has been written

Parameters:

subject (str | tuple | int | bool) –

Return type:

bool

begin_record(class_uri: str, subject: str | tuple | int | bool, is_blank: bool, is_buffered: bool)[source]#

Tell the writer that we are going to write a record, and we already have all information of the record to write. The function return true if this is a new record, otherwise false.

# Arguments

  • class_uri - the URI of the class that the record belongs to

  • subject - real id of the record, which is determined by the value of drepr:uri property

    of the record or generated randomly (if it’s a blank node)

  • is_blank - whether this subject is a blank node or not

Parameters:
end_record()[source]#

Tell the writer that we finish writing all information of the record. This method cannot be called before begin_record method.

Note: this method should not be called if the function begin_record return false

abort_record()[source]#

Abort the record that is being written

is_record_empty() bool[source]#
Return type:

bool

write_data_property(predicate_id: str, value: Any, dtype: Optional[str])[source]#

Write value of a data property of the current record.

# Arguments

  • subject - real id of the current record

  • predicate_id - id of the data property that we are writing to (edge_id of the edge in the

    semantic model)

  • value - value of the property

Parameters:
write_object_property(predicate_id: str, object: str | tuple | int | bool, is_subject_blank: bool, is_object_blank: bool, is_new_subj: bool)[source]#

Write value of a object property of the current record.

# Arguments

  • predicate_id - id of the object property that we are writing to (edge_id of the edge in the

    semantic model)

  • object - id of the target record

  • is_subject_blank - whether the subject id is blank

  • is_object_blank - whether the object id is blank

  • is_new_subj - whether the current record is a new record or an existing record (obtained

    from the begin_record or begin_partial_buffering_record function

Parameters:
write_to_string()[source]#
write_to_file(filepath)[source]#
write_triple(subj: rdflib.term.URIRef | rdflib.term.BNode, pred, obj)[source]#
Parameters:

subj (rdflib.term.URIRef | rdflib.term.BNode) –

begin_partial_buffering_record(subject: str, is_blank: bool) bool#

Tell the writer that we are going to write a record, and we don’t have some information about the links between the records and other records as the other records haven’t been generated yet. The function return true if this is a new record, otherwise false.

# Arguments

  • subject - real id of the record, which is determined by the value of drepr:uri property

    of the record

  • is_blank - whether this subject is a blank node or not

Parameters:
  • subject (str) –

  • is_blank (bool) –

Return type:

bool

buffer_object_property(target_cls: str, predicate_id: str, object: str, is_object_blank: bool)#

Write value of a object property of the current record into buffer because we haven’t generated the target object, it may be missed later.

# Arguments

  • target_cls: id of the class of the target record that the current record is linked to,

    which is the node_id of the class node in the semantic model

  • predicate_id - id of the object property that we are writing to (edge_id of the edge in the

    semantic model)

  • object - id of the target record

  • is_object_blank - whether the object is blank node or not

Parameters:
  • target_cls (str) –

  • predicate_id (str) –

  • object (str) –

  • is_object_blank (bool) –

write_pred_obj(pred, obj)[source]#