Spaces:
Sleeping
Sleeping
| import re | |
| from typing import Dict, List, Union | |
| def product_data_to_str(product_data: Dict[str, Union[str, List[str]]]) -> str: | |
| """ | |
| Convert product data to a string. | |
| Args: | |
| - product_data: a dictionary of product data | |
| Returns: | |
| - a string representation of the product data | |
| """ | |
| if product_data is None: | |
| return "" | |
| data_list = [] | |
| for k, v in product_data.items(): | |
| data_line = None | |
| if isinstance(v, list): | |
| delimiter = "," | |
| for sub_v in v: | |
| if "," in sub_v: | |
| delimiter = ( | |
| ";" # Use semicolon as delimiter if comma is found in the value | |
| ) | |
| for i, sub_v in enumerate(v): | |
| if ";" in sub_v: | |
| v[i] = f'"{sub_v}"' | |
| data_line = f"{k}: {f'{delimiter} '.join(v)}" | |
| elif isinstance(v, str): | |
| data_line = f"{k}: {v}" | |
| else: | |
| raise ValueError( | |
| f"Unsupported data type for value of product data: {type(v)}. Only list and str are supported." | |
| ) | |
| data_list.append(data_line) | |
| return "\n".join(data_list) | |
| def to_snake_case(s): | |
| # Remove leading/trailing whitespace and convert to lowercase | |
| s = s.strip().lower() | |
| # Replace spaces, hyphens, and periods with underscores | |
| s = re.sub(r'[\s\-\.\+]', '_', s) | |
| # Remove any characters that are not alphanumeric or underscores | |
| s = re.sub(r'[^a-z0-9_]', '', s) | |
| # Replace multiple underscores with a single one | |
| s = re.sub(r'_+', '_', s) | |
| # Remove leading digits (Python variable names can't start with a number) | |
| s = re.sub(r'^[0-9]+', '', s) | |
| # Make sure it doesn't start with an underscore and is not empty | |
| if not s or not s[0].isalpha(): | |
| s = 'var_' + s | |
| return s | |