from bs4 import BeautifulSoup
import re


def strip_spacing_from_soup(soup: BeautifulSoup, strip=False, verbose=None) -> BeautifulSoup:
    """
    Strip excess white spaces near punctuation marks, e.g. fix ' .' and ' ,'

    Args:
        soup (BeautifulSoup, Tag, NavigableString): any soup
    Returns:
        soup (BeautifulSoup, Tag, NavigableString): with excess white spaces stripped out
    Modules: 
        bs4 (BeautifulSoup), re
    """
    if verbose is None:
        if not strip:
            verbose=True
    _punctuation_spaces = re.compile(r'\s([?.!,;"](?:\s|$))')
    for item in soup.find_all():
        if item.string:
            s = re.search(_punctuation_spaces, item.string)
            if s:
                if verbose:
                    print(s)
                if strip:
                    item.string.replace_with(re.sub(_punctuation_spaces,  r'\1', item.string))
    return soup