cfpq_data.grammars.readwrite.cfg#

Read (and write) a context-free grammar from (and to) different sources.

Functions

cfg_from_text(text, *[, start_symbol])

Create a context-free grammar [1] from text.

cfg_from_txt(path, *[, start_symbol])

Create a context-free grammar [1] from TXT file.

cfg_to_text(cfg)

Turns a context-free grammar [1] into its text representation.

cfg_to_txt(cfg, path)

Saves a context-free grammar [1] text representation into TXT file.

cfg_from_text(text: str, *, start_symbol: Variable = Variable(S)) → CFG[source]#

Create a context-free grammar [1] from text.

Parameters:
textstr

The text with which the context-free grammar will be created.

start_symbolVariable

Start symbol of a context-free grammar.

Returns:
cfgCFG

Context-free grammar.

References

Examples

>>> from cfpq_data import *
>>> cfg = cfg_from_text("S -> a S b S")
>>> cfg_to_text(cfg)
'S -> a S b S'
cfg_from_txt(path: Path | str, *, start_symbol: Variable = Variable(S)) → CFG[source]#

Create a context-free grammar [1] from TXT file.

Parameters:
pathUnion[Path, str]

The path to the TXT file with which the context-free grammar will be created.

start_symbolVariable

Start symbol of a context-free grammar.

Returns:
cfgCFG

Context-free grammar.

References

Examples

>>> from cfpq_data import *
>>> cfg_1 = cfg_from_text("S -> a S b S | epsilon")
>>> path = cfg_to_txt(cfg_1, "test.txt")
>>> cfg = cfg_from_txt(path)
>>> cfg_to_text(cfg)
'S -> \nS -> a S b S'
cfg_to_text(cfg: CFG) → str[source]#

Turns a context-free grammar [1] into its text representation.

Parameters:
cfgCFG

Context-free grammar.

Returns:
textstr

Context-free grammar text representation.

References

Examples

>>> from cfpq_data import *
>>> cfg = cfg_from_text("S -> a S b S | epsilon")
>>> cfg_to_text(cfg)
'S -> \nS -> a S b S'
cfg_to_txt(cfg: CFG, path: Path | str) → Path[source]#

Saves a context-free grammar [1] text representation into TXT file.

Parameters:
cfgCFG

Context-free grammar.

pathUnion[Path, str]

The path to the TXT file where context-free grammar text representation will be saved.

Returns:
pathPath

The path to the TXT file where context-free grammar text representation will be saved.

References

Examples

>>> from cfpq_data import *
>>> cfg = cfg_from_text("S -> a S b S")
>>> path = cfg_to_txt(cfg, "test.txt")