import re


def clean_filename(name):
    """ Munge a string to avoid characters that might be problematic as
        a filename in some filesystems.
    """
    # The only acceptable characters are alphanumeric (in the current locale)
    # plus a period and dash.
    wordparts = re.split(r"[^\w\.\-]+", name)

    # Filter out empty strings at the beginning or end of the list.
    wordparts = [x for x in wordparts if x]

    # Make sure this is an ASCII-encoded string, not a Unicode string.
    filename = "_".join(wordparts).encode("ascii")

    return filename