pycrossword  0.2
Pure-Python implementation of a crossword puzzle generator and editor
Public Member Functions | Static Public Member Functions | Public Attributes | Private Member Functions | Private Attributes | List of all members
pycross.crossword.Crossword Class Reference

Implementation of a crossword puzzle with auto generation functionality. More...

Public Member Functions

def __init__ (self, data=None, data_type='grid', wordsource=None, wordfilter=None, pos='N', log='stdout', bufferedlog=False, **kwargs)
 Initializes Crossword members. More...
 
def __del__ (self)
 Destructor: flushes and closes log file (if present). More...
 
def init_data (self, **kwargs)
 Initializes the crossword grid data. More...
 
def setlog (self, log='')
 Initializes Crossword::log to point to the relevant output stream. More...
 
def change_word (self, word, new_word)
 Replaces the text representation of a given word. More...
 
def clear_word (self, word, force_clear=False)
 Clears the given word making its characters blank. More...
 
def clear (self)
 Clears the crossword grid (making all words blank). More...
 
def print_used (self)
 Prints all words currently contained in Crossword::used list. More...
 
def closelog (self)
 Flushes and closes Crossword::log if it points to a file. More...
 
def add_completed (self)
 Updates the Crossword::used list adding the completed (pre-set) words. More...
 
def reset_used (self)
 Resets the Crossword::used list (clears and re-adds all completed words). More...
 
def suggest (self, word)
 Fetches suggestions for the given word from the datasets (Crossword::wordsource). More...
 
def make_path (self, start_word=None, path=[], recurse=0, chain_paths=False, word_filter=None)
 Creates a sequential generation path (list of words) forming a connected graph. More...
 
def generate_iter (self, timeout=None, stopcheck=None, on_progress=None)
 Generates crossword using the iterative algorithm. More...
 
def generate_recurse (self, start_word=None, recurse_level=0, timeout=None, stopcheck=None, on_progress=None)
 Generates crossword using the recursice algorithm. More...
 
def timeout_happened (self, timeout=None)
 Checks if the generation operation (or whatever) has timed out. More...
 
def generate (self, method=None, timeout=60.0, stopcheck=None, onfinish=None, ontimeout=None, onstop=None, onerror=None, onvalidate=None, on_progress=None)
 Generates (fills) the crossword (grid) using the given generation method (iterative / recursive). More...
 
def validate (self)
 Validates all completed words against the word list (checks they are all present). More...
 
def __str__ (self)
 String converter operator overload: outputs Crossword object as a crossword grid. More...
 

Static Public Member Functions

def basic_grid (cols, rows, base_pattern=1)
 Creates a crossword grid using one of the four basic 2x2 patterns. More...
 

Public Attributes

 data
 str | list crossword grid source data type as used by crossword::Wordgrid constructor More...
 
 data_type
 str crossword grid source data type as used by crossword::Wordgrid constructor More...
 
 used
 set of used words (to rule out duplicate words in CW) More...
 
 wordsource
 wordsrc::Wordsource source(s) of words to use in generation More...
 
 wordfilter
 callable | None word filtering function used in Crossword::suggest() More...
 
 pos
 str | list | tuple | None word part-of-speech filter More...
 
 bufferedlog
 bool whether the log should be buffered (or written on disk only on destruction) More...
 
 words
 crossword::Wordgrid internal crossword grid object More...
 
 time_start
 float start time - used in generate() to mark elapsed time More...
 
 log
 output stream (file) for debug messages More...
 

Private Member Functions

def _log (self, what, end='\n')
 Prints debug/log message to Crossword::log with optional line-ending char. More...
 

Private Attributes

 _slog
 

Detailed Description

Implementation of a crossword puzzle with auto generation functionality.

This class wraps (incapsulates) crossword::Wordgrid to construct and manipulate the crossword grid on the low level (file I/O, putting and getting individual words and characters, validation etc). It also incorporates a wordsrc::Wordsource object to provide the source (or multiple sources) of words for filling the crossword grid automatically. The filling (generation) is performed by the Crossword::generate() method. Additionally, some useful methods of crossword::Wordgrid are re-implemented to account for used words - see Crossword::used.

Constructor & Destructor Documentation

◆ __init__()

def pycross.crossword.Crossword.__init__ (   self,
  data = None,
  data_type = 'grid',
  wordsource = None,
  wordfilter = None,
  pos = 'N',
  log = 'stdout',
  bufferedlog = False,
**  kwargs 
)

Initializes Crossword members.

Parameters
datastr | list crossword grid source data as used by crossword::Wordgrid constructor
data_typestr crossword grid source data type as used by crossword::Wordgrid constructor
wordsourcewordsrc::Wordsource | None source(s) of words to use in generation
wordfiltercallable | None word filtering function used in Crossword::suggest(). The callback prototype is as follows: (str word) -> bool True if word can be used, False if it must be rejected wordfilter may be None if no filtering is required.
posstr | list | tuple | None word part-of-speech filter: can be a list/tuple (e.g. ['N', 'V']), a single str, e.g. 'N'; the value of 'ALL' or None means no part-of-speech filter
logstr | None stream or file path to output debugging info (log messages); may be one of:
  • 'stdout' (default): current console stream
  • 'stderr': error console stream
  • file path: path to output (text) file
  • empty string or None: no logging will be made
bufferedlogbool whether the log should be buffered (or written on disk only on destruction) or not buffered (default), when log messages will be written immediately
kwargskeyword args additional args passed to crossword::Wordgrid constructor, like: info, on_reset, on_clear, on_change, on_clear_word, on_putchar etc.

◆ __del__()

def pycross.crossword.Crossword.__del__ (   self)

Destructor: flushes and closes log file (if present).

Member Function Documentation

◆ __str__()

def pycross.crossword.Crossword.__str__ (   self)

String converter operator overload: outputs Crossword object as a crossword grid.

◆ _log()

def pycross.crossword.Crossword._log (   self,
  what,
  end = '\n' 
)
private

Prints debug/log message to Crossword::log with optional line-ending char.

Parameters
whatstr debug/log message to print
endstr optional line-ending

◆ add_completed()

def pycross.crossword.Crossword.add_completed (   self)

Updates the Crossword::used list adding the completed (pre-set) words.

◆ basic_grid()

def pycross.crossword.Crossword.basic_grid (   cols,
  rows,
  base_pattern = 1 
)
static

Creates a crossword grid using one of the four basic 2x2 patterns.

Parameters
colsint number of columns in grid, >= 2
rowsint number of rows in grid, >= 2
base_patternint basic 2x2 pattern, one of:
 1 =     [*][_]
         [_][_]
 2 =     [_][*]
         [_][_]
 3 =     [_][_]
         [*][_]
 4 =     [_][_]
         [_][*]
 
Returns
str concatenated (newline-delimited) grid string

◆ change_word()

def pycross.crossword.Crossword.change_word (   self,
  word,
  new_word 
)

Replaces the text representation of a given word.

See description of arguments in Wordgrid::change_word(). Reimplemented to remove the old word from Crossword::used.

◆ clear()

def pycross.crossword.Crossword.clear (   self)

Clears the crossword grid (making all words blank).

See description of arguments in Wordgrid::clear(). Reimplemented to clear Crossword::used.

◆ clear_word()

def pycross.crossword.Crossword.clear_word (   self,
  word,
  force_clear = False 
)

Clears the given word making its characters blank.

See description of arguments in Wordgrid::clear_word(). Reimplemented to remove the old word from Crossword::used.

◆ closelog()

def pycross.crossword.Crossword.closelog (   self)

Flushes and closes Crossword::log if it points to a file.

◆ generate()

def pycross.crossword.Crossword.generate (   self,
  method = None,
  timeout = 60.0,
  stopcheck = None,
  onfinish = None,
  ontimeout = None,
  onstop = None,
  onerror = None,
  onvalidate = None,
  on_progress = None 
)

Generates (fills) the crossword (grid) using the given generation method (iterative / recursive).

Parameters
methodstr: generation method, one of:
  • 'iter': use the iterative algorithm
  • 'recurse': use the recursive algorithm
  • None or empty string (default): use recursive algo if cw is fully blank and iter othwerwise
timeoutfloat: terminate generation after the lapse of this many seconds; if None, no timeout is set
stopcheckcallable: called by generation methods to check if termination is required: see this argument in generate_recurse() and generate_iter()
onfinishcallable: called at completion; callback prototype is: onfinish(elapsed: float) -> None, where elapsed: float: seconds elapsed during generation
ontimeoutcallable: called at timeout error; callback prototype is: ontimeout(timeout: float) -> None, where timeout: float: timeout seconds
onstopcallable: called if the generation was interrupted via stopcheck; prototype is: onstop() -> None
onerrorcallable: called on uncaught exception; prototype is: onerror(err: Exception) -> None, where err: Exception: the raised exception
onvalidatecallable: called on validating cw words; prototype is: onvalidate(bad_words: list or None) -> None, where bad_word: list of unmatched words or None if successful (see validate())
on_progresscallable: callback function to monitor currrent generation progress: see this argument in generate_recurse() and generate_iter()
Returns
bool True on successful generation and False on failure.

◆ generate_iter()

def pycross.crossword.Crossword.generate_iter (   self,
  timeout = None,
  stopcheck = None,
  on_progress = None 
)

Generates crossword using the iterative algorithm.

Warning

Currently the iterative algo does a good job ONLY for fully blank word grids. For partically filled grids, it will generate INCORRECT words, since the traversal path is generated STATICALLY only once and is not amended during word generation. The path exludes all words in USED list, so the algo will fit words without checking how they intersect with existing (used) words in the grid. While this caveat will be dealt with later, prefer the Recursive algo for word grids with some words filled.
Parameters
timeoutfloat timeout in seconds after which time the generation will be interrupted with a CWTimeoutError exception. None value (default) means no timeout check.
stopcheckcallable callback function that must return True to stop the generation and False to continue. IfNoneis passed, no stop check is performed. @param on_progresscallable` callback function to monitor currrent generation progress. Prototype is: ([Crossword] this object, int completed words count, int total words count) -> None
Returns
bool True on success (all words in CW are filled) and False otherwise

◆ generate_recurse()

def pycross.crossword.Crossword.generate_recurse (   self,
  start_word = None,
  recurse_level = 0,
  timeout = None,
  stopcheck = None,
  on_progress = None 
)

Generates crossword using the recursice algorithm.

Parameters
start_wordWord the initial word from which generation will start; if None, the first incomplete word will be taken
recurse_levelint the current recursion depth (position on stack); this arg must be zero when starting generation; each recursive call will increment it and each return will decrement it
timeoutfloat timeout in seconds after which time the generation will be interrupted with a CWTimeoutError exception. None value (default) means no timeout check.
stopcheckcallable callback function that must return True to stop the generation and False to continue. If None is passed, no stop check is performed.
on_progresscallable callback function to monitor currrent generation progress. Prototype is: ([Crossword] this object, int completed words count, int total words count) -> None
Returns
bool True on success (all words in CW are filled) and False otherwise

◆ init_data()

def pycross.crossword.Crossword.init_data (   self,
**  kwargs 
)

Initializes the crossword grid data.

Parameters
kwargskeyword args args passed to crossword::Wordgrid constructor

◆ make_path()

def pycross.crossword.Crossword.make_path (   self,
  start_word = None,
  path = [],
  recurse = 0,
  chain_paths = False,
  word_filter = None 
)

Creates a sequential generation path (list of words) forming a connected graph.

All words in path are connected through intersections. Algorithm starts from first non-complete word (with one or more blanks), then recursively adds each intersecring word using DFS (depth-first search). The resulting path contains all the words in the CW if chain_paths == True, or a single connected graph (list) of words if chain_paths == False.

Parameters
start_wordWord the initial word from which generation will start; if None, the first incomplete word will be taken
pathlist pointer to the list of words forming the path (will be updated by the function)
recurseint the current recursion depth (position on stack); this arg must be zero when starting path generation; each recursive call will increment it and each return will decrement it
chain_pathsbool whether to merge all word graphs together into one path (True), or make one connected path starting from start_word (False). In essence, setting this arg to False (default) may be useful when generating CW block-wise, where each graph (block of words) is not connected with the others by intersections. In this case, concurrent generation might be used.
word_filtercallable filter function to exclude words from search tree. Callback prototype is as follows: (Word object) -> bool True to exclude, False to include in path

◆ print_used()

def pycross.crossword.Crossword.print_used (   self)

Prints all words currently contained in Crossword::used list.

◆ reset_used()

def pycross.crossword.Crossword.reset_used (   self)

Resets the Crossword::used list (clears and re-adds all completed words).

◆ setlog()

def pycross.crossword.Crossword.setlog (   self,
  log = '' 
)

Initializes Crossword::log to point to the relevant output stream.

Parameters
logstr | None output stream for debug messages, any of:
  • 'stdout' (default): standard console output
  • 'stderr': error console stream
  • file path: path to output (text) file
  • empty string or None: no logging will be made
See also
_log()

◆ suggest()

def pycross.crossword.Crossword.suggest (   self,
  word 
)

Fetches suggestions for the given word from the datasets (Crossword::wordsource).

The method accounts for the corresponding rules / filters in Crossword::wordfilter and screens off items found in Crossword::used.

Parameters
wordstr word pattern to look for in the word source (Crossword::wordsource), e.g. 'f_th__' (will fetch 'father')

◆ timeout_happened()

def pycross.crossword.Crossword.timeout_happened (   self,
  timeout = None 
)

Checks if the generation operation (or whatever) has timed out.

The method gets the elapsed time between the current timer and Crossword::time_start and checks this value against its 'timeout' argument.

Parameters
timeoutfloat | int timeout value to check (in seconds)
Returns
bool True if the elapsed time is equal or greater than timeout; False otherwise

◆ validate()

def pycross.crossword.Crossword.validate (   self)

Validates all completed words against the word list (checks they are all present).

Returns
list | None list of unmatched words (those not found in Crossword::wordsource) or None if all words were matched

Member Data Documentation

◆ _slog

pycross.crossword.Crossword._slog
private

◆ bufferedlog

pycross.crossword.Crossword.bufferedlog

bool whether the log should be buffered (or written on disk only on destruction)

◆ data

pycross.crossword.Crossword.data

str | list crossword grid source data type as used by crossword::Wordgrid constructor

◆ data_type

pycross.crossword.Crossword.data_type

str crossword grid source data type as used by crossword::Wordgrid constructor

◆ log

pycross.crossword.Crossword.log

output stream (file) for debug messages

◆ pos

pycross.crossword.Crossword.pos

str | list | tuple | None word part-of-speech filter

◆ time_start

pycross.crossword.Crossword.time_start

float start time - used in generate() to mark elapsed time

◆ used

pycross.crossword.Crossword.used

set of used words (to rule out duplicate words in CW)

◆ wordfilter

pycross.crossword.Crossword.wordfilter

callable | None word filtering function used in Crossword::suggest()

◆ words

pycross.crossword.Crossword.words

crossword::Wordgrid internal crossword grid object

◆ wordsource

pycross.crossword.Crossword.wordsource

wordsrc::Wordsource source(s) of words to use in generation


The documentation for this class was generated from the following file: