我正在尝试从文件中获取城市、州,然后获取指示区域的数字。然后,我需要对具有相同城市和州的另一个文件执行相同的操作,其中的数字表示人口,并以相同的格式创建人口密度文件。我不明白我应该如何去做这件事
我是 py 新手,没有很多编码经验,所以这就是我到目前为止所拥有的
这是人口txt文件:
Calico, California 12
Rhyolite, Nevada 3
Goldfield, Arizona 30
St. Elmo, Colorado 6
Terlingua, Texas 100
Virginia City, Montana 10
Nevada City, Montana 12
Bodie, California 45
Cahawba, Alabama 22
Kennecott, Alaska 2
Bannack, Montana 233
South Pass City, Wyoming 43
Centralia, Pennsylvania 6
Thurmond, West Virginia 55
Glenrio, Texas 1
Glenrio, New Mexico 1
Bulowville, Florida 54
这里是区域txt文件:
Calico, California 2
Rhyolite, Nevada 3
Goldfield, Arizona 12
St. Elmo, Colorado 4
Terlingua, Texas 10
Virginia City, Montana 15
Nevada City, Montana 6
Bodie, California 100
Cahawba, Alabama 20
Kennecott, Alaska 300
Bannack, Montana 23
South Pass City, Wyoming 3
Centralia, Pennsylvania 6
Thurmond, West Virginia 50
Glenrio, Texas 1
Glenrio, New Mexico 1
Bulowville, Florida 60
我知道我需要做一些事情:
OpenFile = open( Population.txt', 'r')
for EachLine in OpenFile:
Split = EachLine.strip.split(" ")
#some sort of append to a list but with the first part of split in one list and the number
# nested in that list
OpenFile.close()
考虑将您的任务分解为步骤并为每个步骤创建辅助函数:
from pathlib import Path
def read_data(filename: Path) -> dict[str, int]:
"""Reads data from a given filename and parses it into a dictionary.
Expected file only has lines with 'City, State' followed by whitespace and a integer.
Args:
filename (Path): The path to the file to read.
Returns:
A dictionary where keys are 'City, State' and values are integers.
"""
data = {}
with open(filename, 'r') as file:
for line in file:
line = line.strip()
if line:
parts = line.rsplit(' ', 1)
name = parts[0].strip()
number = int(parts[1])
data[name] = number
return data
def calculate_density(population_data: dict[str, int],
area_data: dict[str, int]) -> dict[str, float]:
"""Calculates the population density by dividing the population by the area.
Args:
population_data: A dictionary of populations keyed by 'City, State'.
area_data: A dictionary of areas keyed by 'City, State'.
Returns:
A dictionary of population densities keyed by 'City, State'.
"""
return {
city_state: population / area_data[city_state]
for city_state, population in population_data.items()
if city_state in area_data
}
def write_data(filename: Path, data: dict[str, float]) -> None:
"""Writes data dict to a file after sorting, with each key-value pair on a new line.
Args:
filename: The path to the file where data will be written.
data: The data to write, where each key-value pair is a line.
"""
with open(filename, 'w') as file:
for key, value in sorted(data.items()):
file.write(f"{key} {value:.2f}\n")
def main() -> None:
"""Entry point of script."""
write_data(filename=Path('density.txt'),
data=calculate_density(
population_data=read_data(Path('population.txt')),
area_data=read_data(Path('area.txt')),
))
if __name__ == '__main__':
main()
输出
density.txt
:
Bannack, Montana 10.13
Bodie, California 0.45
Bulowville, Florida 0.90
Cahawba, Alabama 1.10
Calico, California 6.00
Centralia, Pennsylvania 1.00
Glenrio, New Mexico 1.00
Glenrio, Texas 1.00
Goldfield, Arizona 2.50
Kennecott, Alaska 0.01
Nevada City, Montana 2.00
Rhyolite, Nevada 1.00
South Pass City, Wyoming 14.33
St. Elmo, Colorado 1.50
Terlingua, Texas 10.00
Thurmond, West Virginia 1.10
Virginia City, Montana 0.67