0

Processing multiple text files using python

Included in USAOnline is the baby name file for 1986 (yob1986.txt). For this
assignment, you will need to read in both the 1986 and 2016 (yob2016.txt) files. The user
should enter a baby name to search for. Your program should not only give the total (not separated
by gender) number of babies named that for both 1986 and 2016, but also give the percentage
change from 1986 to 2016 for that name

Code

f = open("yob2016.txt")
f2 = open("yob1986.txt")
names_data_2016 = {}
names_data_1986 = {}
for row in f:
row = row.rstrip()
data = row.split(",")
name = data[0]
count = int(data[2])
if name not in names_data_2016.keys():
names_data_2016[name] = 0
names_data_2016[name] += count

for row in f2:
row = row.rstrip()
data = row.split(",")
name = data[0]
count = int(data[2])
if name not in names_data_1986.keys():
names_data_1986[name] = 0
names_data_1986[name] += count

name = input("Enter name : ").title()
if name in names_data_2016 and name in names_data_1986:
count_2016 = names_data_2016[name]
count_1986 = names_data_1986[name]
print(name,"in 2016 counts =",count_2016)
print(name,"in 1986 counts =",count_1986)
total = count_2016 + count_1986
change = count_2016 - count_1986
st = "increases"
if change < 0:
st = "decreases"
change = change * -1
percentage = round((change * 100) / total,2)
print(f"Percentage change from 1986 to 2016 {st} by {percentage}%")
else:
print("Name not in files")

Output

keep visiting : shaadcoding

shaad

Leave a Reply

Your email address will not be published. Required fields are marked *