网页抓取后:如何将带K/M/B后缀的货币值转为无逗号整数?
Got it, let's tackle this currency suffix conversion issue you're facing! I've dealt with similar problems in web scraping before, so here's a reliable solution you can drop right into your code:
Step 1: Create a Conversion Function
This function handles comma-separated values, case-insensitive suffixes (K/k, M/m, B/b), and edge cases like non-standard inputs:
def convert_currency(value_str): # Remove commas first to handle values like "1,234K" cleaned_value = value_str.replace(',', '') # Define suffix-to-multiplier mapping (covers both uppercase and lowercase) suffix_map = { 'K': 10**3, 'M': 10**6, 'B': 10**9, 'k': 10**3, 'm': 10**6, 'b': 10**9 } # Check if the last character is a recognized suffix if cleaned_value and cleaned_value[-1] in suffix_map: num_part = cleaned_value[:-1] suffix = cleaned_value[-1] try: # Convert to float, multiply by suffix multiplier, then cast to integer converted = float(num_part) * suffix_map[suffix] # Return integer if it's a whole number, otherwise round to nearest integer return int(converted) if converted.is_integer() else int(round(converted)) except ValueError: # Fallback if the number part is invalid (return original string or adjust as needed) return value_str else: # No suffix, convert directly to integer try: return int(cleaned_value) except ValueError: return value_str
Step 2: How to Use It in Your Scraping Script
Once you've grabbed the currency value from the website, just pass it to this function to get the integer version, then compare it against your minimum value:
# Example usage with your group_id context scraped_value = "2.5M" # Replace with your actual scraped data min_value = 1000000 # Your defined minimum threshold converted_num = convert_currency(scraped_value) if converted_num >= min_value: print(f"Group ID {group_id}: Value {converted_num} meets or exceeds minimum") else: print(f"Group ID {group_id}: Value {converted_num} is below minimum")
Test Cases to Verify
Here’s how the function handles common scenarios:
convert_currency("1K")→1000convert_currency("3.7M")→3700000convert_currency("1,500B")→1500000000000convert_currency("750")→750convert_currency("invalid")→"invalid"(safe fallback)
This approach is flexible and should cover most cases you’ll encounter in web-scraped currency values. Feel free to tweak the suffix map or fallback behavior if you need to support additional suffixes (like 'G' for billions in some regions).
内容的提问来源于stack exchange,提问作者Happy

