Skip to content

Functions:

  • get_valid_filename

    Convert strings to valid file names. Calls get_valid_name

  • get_valid_name

    Return the given string converted to a string that can be used for a clean filename.

  • get_valid_var_name

    Convert strings to valid variable names. Calls get_valid_name

get_valid_filename

get_valid_filename(name)

Convert strings to valid file names. Calls get_valid_name

Source code in src/rdf_utils/naming.py
39
40
41
def get_valid_filename(name: str) -> str:
    """Convert strings to valid file names. Calls `get_valid_name`"""
    return get_valid_name(name, __FILENAME_REPLACEMENTS)

get_valid_name

get_valid_name(name, replacement_dict)

Return the given string converted to a string that can be used for a clean filename.

Based on same function from https://github.com/django/django/blob/main/django/utils/text.py also convert ':' to '__' and '/' to '_'

Remove leading and trailing spaces; convert other spaces to underscores; and remove anything that is not an alphanumeric, dash, underscore, or dot.

Parameters:

  • name (str) –

    String name to be converted

  • replacement_dict (dict) –

    Maps special characters to acceptable replacements

Examples:

>>> get_valid_filename("john's portrait in 2004.jpg")
'johns_portrait_in_2004.jpg'
Source code in src/rdf_utils/naming.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def get_valid_name(name: str, replacement_dict: dict) -> str:
    """Return the given string converted to a string that can be used for a clean filename.

    Based on same function from https://github.com/django/django/blob/main/django/utils/text.py
    also convert ':' to '__' and '/' to '_'

    Remove leading and trailing spaces; convert other spaces to underscores;
    and remove anything that is not an alphanumeric, dash, underscore, or dot.

    Parameters:
        name: String name to be converted
        replacement_dict: Maps special characters to acceptable replacements

    Examples:
        >>> get_valid_filename("john's portrait in 2004.jpg")
        'johns_portrait_in_2004.jpg'
    """
    s = str(name).strip()
    for char in replacement_dict:
        s = s.replace(char, replacement_dict[char])

    # remove remaining characters
    s = re.sub(r"(?u)[^-\w.]", "", s)
    if s in {"", ".", ".."}:
        # suspicious file name
        raise ValueError(f"Could not derive file name from '{name}'")
    return s

get_valid_var_name

get_valid_var_name(name)

Convert strings to valid variable names. Calls get_valid_name

Source code in src/rdf_utils/naming.py
44
45
46
def get_valid_var_name(name: str) -> str:
    """Convert strings to valid variable names. Calls `get_valid_name`"""
    return get_valid_name(name, __VAR_NAME_REPLACEMENTS)