[Python] Issue in Python function to eliminate prefix and remain the subsequent value

Discussão em 'Python' iniciado por Stack, Maio 5, 2025.

  1. Stack

    Stack Membro Participativo

    I have a python function that is defined to clean a certain column. The function has the following criteria which are as per below:

    1. If product_xml contains NULL or None, return as None.
    2. If product_xml starts with a prefix "TEST ", cut off the prefix keep the value.
    3. If product_xml equals "ABC", return as None.
    4. If product_xml contains "_", "-", ".", "," take the first part only and cut off the remaining.
    5. Check if
    • remainder ends with XX or XY or YY, return as None.
    • remainder has less than 2 digits, return as None.
    1. Else, call back product family function and return NONE as UNKNOWN.

    '''

    def product_xml_cleaned(product_xml):
    if product_xml is None or str(product_xml).lower() == "none":
    return None

    # Remove prefix that begins with TEST or ABC
    if product_xml.startswith("TEST "):
    product_xml = product_xml[len("TEST ") :].strip()
    if product_xml == "ABC":
    return None

    # Take first part and remove "_", "-", ".", ","
    for delimiter in ["_", "-", ".", ","]:
    if delimiter in product_xml:
    product_xml = product_xml.split(delimiter)[0]
    break

    # check if product family ends with XX, XY, YY, xy
    if product_xml.endswith(("XX", "XY", "YY", "xy")):
    return None

    # Count remainder, must be less than 2
    digit_count = sum(a.isdigit() for a in product_xml)
    if digit_count < 2:
    return None

    return product_xml

    def get_product_family_a2mm(product_xml: str):
    """
    Filter out invalid A2MM product names and only derive product family values.
    """
    # Part 1:get the clean product_xml value
    cleaned = product_xml_cleaned(product_xml)

    # Part 2: get product family function and call back
    if cleaned is None:
    product_family = None
    else:
    product_family, _ = extract_product_family_and_product_name(part_name=cleaned)

    # Part 3: Replace None with UNKNOWN
    return product_family if product_family is not None else "UNKNOWN"


    '''

    My code works exactly as how it's supposed to except for the prefix part. One of the cases is to eliminate the prefix that starts with "TEST " and keep the remaining value. For example, if product_xml contains "TEST AB9305", it should be shown as "AB9305". However the function is showing the value as "AB930".

    Upon checking I notice that the function I made above is colliding with an existing function that is as per below.

    ProductType.TEST_FALLBACK: r"^([A-Z]{2,3}[0-9]{2,3})([A-Z0-9]{0,1})?.*"


    How do I edit my product_xml_cleaned function without making changes to the ProductType.TEST_FALLBACK function?

    Continue reading...

Compartilhe esta Página