Python键错误:“C”

2024-04-26 05:47:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为对数表编写代码。输出应该是三行表示城市总数、唯一人口计数和第一位数频率分布,然后是三列表示数字、计数和百分比

这是我当前的代码:

    
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'

你知道这个错误的具体用途吗?你知道如何修复它吗? 抱歉,代码太长了


Tags: ofthetointxtforcountline
1条回答
网友
1楼 · 发布于 2024-04-26 05:47:09

正如其他人所指出的,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

祝你好运

相关问题 更多 >