Python 3.8.10环境下类Switch/Case语句适配:文件名标准化处理方案咨询
Great question! Since Python 3.8 doesn't support the match/case syntax introduced in 3.10, we can leverage Python's core strengths—like dictionary mappings, clean iteration, and straightforward class design—to replace that messy nested if/elif chain with something far more readable and maintainable. Let's walk through a few better approaches:
Option 1: Dictionary-Driven Matching (Simplest & Most Pythonic)
This approach cuts out the nested conditionals entirely by using a priority-ordered list of base prefixes, then appending the required suffix if present. It's lightweight and easy to update:
import random sampleKeys = [ 'transaction_recipient_notification_status_sent/transaction_recipient_notification_status_sent_2021_10_29_12_02_14.snappy', 'transaction_recipient_payment_status_success/transaction_recipient_payment_status_success_2021_10_29_12_02_14.snappy', 'transaction_recipient_verification_rvdm_failure/transaction_recipient_verification_rvdm_failure_2021_10_29_12_02_14.snappy', 'transaction_recipient_verification_rvdm_failure_field_results/transaction_recipient_verification_rvdm_failure_2021_10_29_12_02_14.snappy', 'transaction_recipient_authentication_status_success/transaction_recipient_authentication_status_success_2021_10_29_12_02_14.snappy', 'transaction_recipient_authentication_status_success_field_results/transaction_recipient_authentication_status_success_2021_10_29_12_02_14.snappy', 'transaction_account_tokenization_success/transaction_account_tokenization_success_2021_10_29_12_02_14.snappy', 'transaction_account_tokenization_success_issuers/transaction_account_tokenization_success_2021_10_29_12_02_14.snappy', 'transaction_recipient_payment_status_terminated/transaction_recipient_payment_status_terminated_2021_10_29_12_02_14.snappy', 'transaction_recipient_verification_rvdm_success/transaction_recipient_verification_rvdm_success_2021_10_29_12_02_14.snappy', 'transaction_recipient_verification_rvdm_success_field_results/transaction_recipient_verification_rvdm_success_2021_10_29_12_02_14.snappy', 'transaction_recipient_notification_status_received/transaction_recipient_notification_status_received_2021_10_29_12_02_14.snappy', 'transaction_recipient_authentication_status_success/transaction_recipient_authentication_status_success_2021_10_29_11_17_45.snappy' ] def get_standardized_prefix(key): # Define base prefixes in priority order (matches your original if/elif sequence) base_prefixes = [ 'transaction_recipient_notification', 'transaction_recipient_authentication', 'transaction_recipient_verification', 'transaction_account_verification', 'transaction_account_tokenization', 'transaction_recipient_payment' ] # Find the first matching base prefix base_prefix = next(prefix for prefix in base_prefixes if prefix in key) # Append suffix if needed if '_issuers' in key: return f"{base_prefix}_issuers" elif '_field_results' in key: return f"{base_prefix}_field_results" return base_prefix # Test it out key = random.choice(sampleKeys) print(f'BEFORE ===> {key}') print(f'AFTER ===> {get_standardized_prefix(key)}')
Option 2: Clean Class-Based Implementation
If you prefer encapsulating this logic in a class (for state management or reusability), we can simplify your original class by removing redundant regex and splitting responsibilities into small, clear methods:
class PrefixExtractor: # Class-level constants for easy maintenance BASE_PREFIXES = [ 'transaction_recipient_notification', 'transaction_recipient_authentication', 'transaction_recipient_verification', 'transaction_account_verification', 'transaction_account_tokenization', 'transaction_recipient_payment' ] VALID_SUFFIXES = ['_issuers', '_field_results'] def __init__(self, key): self.key = key self._base_prefix = self._find_base_prefix() self._suffix = self._find_suffix() def _find_base_prefix(self): # Return the first matching base prefix return next(prefix for prefix in self.BASE_PREFIXES if prefix in self.key) def _find_suffix(self): # Return the matching suffix (or empty string if none) for suffix in self.VALID_SUFFIXES: if suffix in self.key: return suffix return '' @property def standardized_prefix(self): # Combine base and suffix for the final result return f"{self._base_prefix}{self._suffix}" # Test the class key = random.choice(sampleKeys) print(f'BEFORE ===> {key}') extractor = PrefixExtractor(key) print(f'AFTER ===> {extractor.standardized_prefix}')
Option 3: Single Regex Match (For Pattern Lovers)
If you want a one-step regex solution, you can build a pattern that matches the base prefix plus an optional valid suffix. This works well if you're comfortable with regex syntax:
import re def get_standardized_prefix_regex(key): # Build a regex pattern that matches any base prefix + optional suffix pattern = re.compile( r'(transaction_recipient_notification|transaction_recipient_authentication|transaction_recipient_verification|transaction_account_verification|transaction_account_tokenization|transaction_recipient_payment)(?:_issuers|_field_results)?' ) match = pattern.search(key) return match.group(0) # Test it key = random.choice(sampleKeys) print(f'BEFORE ===> {key}') print(f'AFTER ===> {get_standardized_prefix_regex(key)}')
Notes on Your Original Implementation
Your initial class approach was on the right track, but a couple of tweaks would make it better:
- The
+in your regex patterns (transaction_recipient_notification+) is unnecessary—re.searchlooks for the substring, and the+would only match repeated characters at the end of the prefix, which isn't what you need. - Using Python's
inoperator for substring checks is simpler and more efficient than regex here, since we don't need complex pattern matching.
All of these approaches avoid the messy nested if/elif chain while staying true to Python's "simple is better than complex" philosophy.
内容的提问来源于stack exchange,提问作者Matt_Davis

