【发布时间】:2021-04-24 17:36:15
【问题描述】:
我正在尝试编写对数表。输出应该是三行表示城市总数、唯一人口计数和第一位频率分布,然后是三列表示数字、计数和百分比。
这是我当前的代码:
def main():
population=set()
#declaring dictionary to hold the count of #each digit
digits={}
#initializing totCities to 0 that holds the count of total number of cities
totCities=0
#initializing all digits in the dictionary to 0
for i in range(1, 10):
num=str(i)
num=num[0]
digits[num]=0
#opening Census_2009.txt file
try:
infile=open("Census_2009.txt",'r')
#throwing error if file cannot be opened and exiting the program
except OSError:
print("Could not open file")
exit()
#ignoring the headernext(infile)
#iterating through each line in file
for i in infile:
#incrementing totCities for each city
totCities+=1
line=i.rstrip().split('\t')
#adding each population count to the set and incrementing the count of the first digit in #the dictionary
population.add(line[-1])
digits[line[-1][0]]+=1
#closing Census_2009.txt
fileinfile.close()
#opening benford.txt file to write the Output
outfile=open("benford.txt",'w')
print("Output written to benford.txt")
#writing the output to the file
outfile.write("Total number of cities: {}\n".format(totCities))
outfile.write("Unique population counts: {}\n".format(len(population)))
outfile.write("Digit\tCount\tPercentage\n")
for key, value in digits.items():
outfile.write("{}\t{}\t{}\n".format(key, value, round(((value/totCities)*100), 1)))
#closing benford.txt
fileoutfile.close()
main()
但是,我收到此错误:
File "<ipython-input-15-061b69b87f23>", line 28, in main
digits[line[-1][0]]+=1
KeyError: 'C'
你知道这个错误具体是为了什么,以及如何修复它吗? 抱歉,代码太长了。
【问题讨论】:
-
需要一个文件样本以便重现
-
欢迎来到 Stack Overflow!请阅读How to debug small programs。您还可以使用Python-Tutor,它有助于逐步可视化代码的执行。
-
line是一个字符串列表。所以line[-1]是一个字符串,line[-1][0]只是一个字符,即'C'。由于数字仅包含1-9,因此当被要求输入digits['C']时会给出KeyError