Python新手求助:从文件读取数据并生成人口密度文件的实现方案
Complete Implementation Guide
Core Approach
Use dictionaries to map each city-state combination to its population and area values. This allows easy lookup to compute population density (population divided by area) and ensures we can align data correctly between the two files.
Step-by-Step Breakdown
1. Read Population Data
We'll read population.txt and store each entry in a dictionary where the key is the city-state string, and the value is the population count.
# Initialize empty dictionary to store population data population_data = {} # Use 'with' to handle file opening/closing automatically with open('population.txt', 'r') as file: for line in file: # Remove leading/trailing whitespace (like newlines) cleaned_line = line.strip() # Skip empty lines if present if not cleaned_line: continue # Split line into parts using any whitespace as separator parts = cleaned_line.split() # Extract population (last element, convert to integer) population = int(parts[-1]) # Reconstruct city-state string from remaining parts city_state = ' '.join(parts[:-1]) # Add entry to dictionary population_data[city_state] = population
2. Read Area Data
Repeat the same process for area.txt to store area values in another dictionary.
# Initialize empty dictionary to store area data area_data = {} with open('area.txt', 'r') as file: for line in file: cleaned_line = line.strip() if not cleaned_line: continue parts = cleaned_line.split() area = int(parts[-1]) city_state = ' '.join(parts[:-1]) area_data[city_state] = area
3. Calculate Density and Write Output
Iterate through the city-state entries, compute density, and write to a new file density.txt in a format matching the input files.
# Open output file for writing with open('density.txt', 'w') as output_file: # Loop through each city-state in the population dataset for city_state in population_data: # Retrieve corresponding population and area values pop = population_data[city_state] area = area_data[city_state] # Calculate density (avoid division by zero) density = pop / area if area != 0 else 0.0 # Format line to match input style: left-align city-state, then density # Adjust the 30-character width to match your input's spacing formatted_line = f"{city_state:<30} {density:.2f}\n" output_file.write(formatted_line)
Full Working Code
Combine all parts into a single script:
# Read population data population_data = {} with open('population.txt', 'r') as file: for line in file: cleaned_line = line.strip() if not cleaned_line: continue parts = cleaned_line.split() population = int(parts[-1]) city_state = ' '.join(parts[:-1]) population_data[city_state] = population # Read area data area_data = {} with open('area.txt', 'r') as file: for line in file: cleaned_line = line.strip() if not cleaned_line: continue parts = cleaned_line.split() area = int(parts[-1]) city_state = ' '.join(parts[:-1]) area_data[city_state] = area # Calculate and write density data with open('density.txt', 'w') as output_file: for city_state in population_data: pop = population_data[city_state] area = area_data[city_state] density = pop / area if area != 0 else 0.0 # Format to match input spacing (adjust 30 to fit your needs) output_file.write(f"{city_state:<30} {density:.2f}\n")
Key Notes
- File handling with
with: This ensures files are properly closed after use, even if an error occurs (better practice than manualopen()/close()). - Variable whitespace handling: Using
split()without arguments splits on any whitespace, which works better than fixed-space splits since input lines have inconsistent spacing. - Density formatting: The
.2fformat rounds density to 2 decimal places. Change this to.0ffor integer values or adjust the decimal count as needed. - Error prevention: Added a check for division by zero to avoid runtime crashes if any area value is zero.
内容的提问来源于stack exchange,提问作者J J
相关产品推荐
相关产品推荐

