def keyword_in_context(text, keyword, ignore_case=True,
                       window_width=50, print_only=True):
    """
    Search for ``keyword`` in ``text`` via regular expression, return or print strings
    spanning ``window_width`` characters before and after each occurrence of keyword.

    Args:
        text (str): text in which to search for ``keyword``
        keyword (str): technically, any valid regular expression string should work,
            but usually this is a single word or short phrase: "spam", "spam and eggs";
            to account for variations, use regex: "[Ss]pam (and|&) [Ee]ggs?"

            N.B. If keyword contains special characters, be sure to escape them!!!
        ignore_case (bool, optional): if True, ignore letter case in `keyword` matching
        window_width (int, optional): number of characters on either side of
            `keyword` to include as "context"
        print_only (bool, optional): if True, print out all results with nice
            formatting; if False, return all (pre, kw, post) matches as generator
            of raw strings

    Returns:
        generator(tuple(str, str, str)), or None
    """
    flags = re.IGNORECASE if ignore_case is True else 0
    if print_only is True:
        for match in re.finditer(keyword, text, flags=flags):
            print('{pre} {kw} {post}'.format(
                    pre=text[max(0, match.start() - window_width): match.start()].rjust(window_width),
                    kw=match.group(),
                    post=text[match.end(): match.end() + window_width].ljust(window_width)))
    else:
        return ((text[max(0, match.start() - window_width): match.start()],
                 match.group(),
                 text[match.end(): match.end() + window_width])
                for match in re.finditer(keyword, text, flags=flags))
dataset/ETHPy150Open chartbeat-labs/textacy/textacy/text_utils.py/keyword_in_context/original