def word_count(ctx, text, by_spaces=False): """ Returns the number of words in the given text string """ text = conversions.to_string(text, ctx) by_spaces = conversions.to_boolean(by_spaces, ctx) return len(__get_words(text, by_spaces))
def word_slice(ctx, text, start, stop=0, by_spaces=False): """ Extracts a substring spanning from start up to but not-including stop """ text = conversions.to_string(text, ctx) start = conversions.to_integer(start, ctx) stop = conversions.to_integer(stop, ctx) by_spaces = conversions.to_boolean(by_spaces, ctx) if start == 0: raise ValueError("Start word cannot be zero") elif start > 0: start -= 1 # convert to a zero-based offset if stop == 0: # zero is treated as no end stop = None elif stop > 0: stop -= 1 # convert to a zero-based offset words = __get_words(text, by_spaces) selection = operator.getitem(words, slice(start, stop)) # re-combine selected words with a single space return ' '.join(selection)
def word_slice(ctx, text, start, stop=0, by_spaces=False): """ Extracts a substring spanning from start up to but not-including stop """ text = conversions.to_string(text, ctx) start = conversions.to_integer(start, ctx) stop = conversions.to_integer(stop, ctx) by_spaces = conversions.to_boolean(by_spaces, ctx) if start == 0: raise ValueError("Start word cannot be zero") elif start > 0: start -= 1 # convert to a zero-based offset if stop == 0: # zero is treated as no end stop = None elif stop > 0: stop -= 1 # convert to a zero-based offset words = __get_words(text, by_spaces) selection = operator.getitem(words, slice(start, stop)) # re-combine selected words with a single space return " ".join(selection)
def _or(ctx, *logical): """ Returns TRUE if any argument is TRUE """ for arg in logical: if conversions.to_boolean(arg, ctx): return True return False
def _and(ctx, *logical): """ Returns TRUE if and only if all its arguments evaluate to TRUE """ for arg in logical: if not conversions.to_boolean(arg, ctx): return False return True
def _if(ctx, logical_test, value_if_true=0, value_if_false=False): """ Returns one value if the condition evaluates to TRUE, and another value if it evaluates to FALSE """ return value_if_true if conversions.to_boolean(logical_test, ctx) else value_if_false