Spaces:
Sleeping
Sleeping
File size: 1,843 Bytes
9645c29 638f225 8ba64a4 9bb2fc2 9645c29 |
1 2 3 4 5 6 7 8 9 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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
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
|