如何在C++中读取文件内带逗号分隔的数字并转为整数?
Great question! You don’t need regex for this—there are simpler, more readable ways to handle comma-separated numbers when reading from CSV. Let’s break down two common approaches depending on what tools you’re using:
Basic Python (No External Libraries)
If you’re using Python’s built-in csv module, you can easily strip the commas from the string value before converting it to an integer. This is straightforward and avoids regex entirely.
Here’s a quick example:
import csv # Open your CSV file with open('your_data.csv', 'r') as csv_file: csv_reader = csv.reader(csv_file) # Skip header row if you have one next(csv_reader) for row in csv_reader: # Assume the number is in the first column (adjust index as needed) number_string = row[0] # Remove all commas from the string cleaned_string = number_string.replace(',', '') # Convert to integer number_integer = int(cleaned_string) # Now you can store or use the integer print(number_integer) # Outputs 1000000 for "1,000,000"
Using Pandas (For Larger Datasets)
If you’re working with bigger datasets and using pandas, it has a built-in parameter to handle thousands separators directly when reading the CSV. This saves you from manually cleaning each value.
Example:
import pandas as pd # Read CSV, specifying the thousands separator df = pd.read_csv('your_data.csv', thousands=',') # The column containing comma-separated numbers will now be an integer (or float if decimals exist) # Verify the data type print(df['your_number_column'].dtype) # Should show int64 (or similar)
A Quick Note on Regex
While regex could work here (e.g., re.sub(r',', '', number_string)), it’s overkill for this simple task. The str.replace() method is faster, more readable, and easier to maintain—especially if you’re not comfortable with regex syntax.
内容的提问来源于stack exchange,提问作者wolnio

