问题描述
我正在尝试编写对数表的代码。输出应该是城市总数、唯一人口计数和第一位数字频率分布的三行,然后是数字、计数和百分比的三列。
这是我当前的代码:
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'
解决方法
正如其他人指出的那样,print(line[-1][0])
可能给出了您意想不到的东西,即 'C'
而不是数字。我们看不到您的输入数据,很难知道这是数据不一致的问题,还是您选择了错误的字段。
如果您确信您的代码选择了正确的字段,但偶尔会忽略一行数据,您可以使用类似的内容对该部分进行快速的部分防弹处理
pop_field = line[-1]
if pop_field.is_numeric():
population.add(pop_field)
lead_char = pop_field[0]
if lead_char.isnumeric():
digits[lead_char]+=1
其他一些不请自来的提示,接受或放弃:
- 您可能只使用整数 1-9 作为字典键,而不是转换为字符串。
- 可以使用快捷方式来初始化字典,比如
digits = dict((d,0) for d in range(1,10))
# digits will be {1: 0,2: 0,3: 0,4: 0,5: 0,6: 0,7: 0,8: 0,9: 0}
- 对于计数任务,
collections
模块具有处理大多数用例的Counter
类。
祝你好运!