import re


def add_subgroup_columns_from_text(
    df, text_column, subgroups, expect_spaces_around_words=True
):
    """Adds a boolean column for each subgroup to the data frame.

    New column contains True if the text contains that subgroup term.

    Args:
      df: Pandas dataframe to process.
      text_column: Column in df containing the text.
      subgroups: List of subgroups to search text_column for.
      expect_spaces_around_words: Whether to expect subgroup to be surrounded by
        spaces in the text_column.  Set to False to for languages which do not
        use spaces.
    """
    ndf = df.copy()
    for term in subgroups:
        if expect_spaces_around_words:
            # pylint: disable=cell-var-from-loop
            ndf[term] = ndf[text_column].apply(
                lambda x: bool(
                    re.search("\\b" + term + "\\b", x, flags=re.UNICODE | re.IGNORECASE)
                )
            )
        else:
            ndf[term] = ndf[text_column].str.contains(term, case=False)
    return ndf