Python键错误:';C';
我正在尝试为对数表编写代码。输出应该是三行表示城市总数、唯一人口计数和第一位数频率分布,然后是三列表示数字、计数和百分比 这是我当前的代码:Python键错误:';C';,python,keyerror,Python,Keyerror,我正在尝试为对数表编写代码。输出应该是三行表示城市总数、唯一人口计数和第一位数频率分布,然后是三列表示数字、计数和百分比 这是我当前的代码: def main(): population=set() #declaring dictionary to hold the count of #each digit digits={} #initializing totCities to 0 that holds the count of
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'
文件“”,第28行,主
数字[行[-1][0]+=1
键错误:“C”
你知道这个错误的具体用途吗?你知道如何修复它吗?
很抱歉代码太长。正如其他人指出的那样,
打印(第[-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)表示范围(1,10)中的d)
#数字将是{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0}
- 对于计数任务,
模块有一个处理大多数用例的集合
类计数器
祝你好运 需要一个文件的样本,所以它的可复制性会来堆栈溢出!请阅读。您还可以使用它帮助逐步可视化代码的执行。
line
是字符串列表。因此,行[-1]
是一个字符串,行[-1][0]
只是一个字符,即“C”。由于数字只包含1-9
,当要求数字['C']