我正在嘗試使用 csv 檔案創建選單程式,方法是向用戶詢問 5 個 ncic 代碼并將該資訊保存為 json 檔案。
這里有幾件事是錯誤的:
export_data()不管用。Traceback (most recent call last): File "C:\Users\dddst279\My Files\Google Drive\My Drive\Final Project - Deidra Dayak.py", line 254, in <module> main() File "C:\Users\dddst279\My Files\Google Drive\My Drive\Final Project - Deidra Dayak.py", line 203, in main export_data(count_ncic_code_dict, count_district_dict, count_beat_dict) File "C:\Users\dddst279\My Files\Google Drive\My Drive\Final Project - Deidra Dayak.py", line 139, in export_data if main_dict['count of crime by ncic code'] is None: KeyError: 'count of crime by ncic code'我正在嘗試制作來自用戶的 5 個 ncic 代碼的條形圖(并將其保存為 png),但是,我有一個圖表,但它是空白的。
TypeError: bar() missing 1 required positional argument: 'height'我嘗試
exit()在main()選項 4 中,但它沒有退出。
我一遍又一遍地看著這個,我被困住了,迷路了,我累了。如果有人有一些想法,我將不勝感激。
這是我的全部代碼。
import matplotlib.pyplot as plt
import json
import csv
#create list
def create_list():
'''Create list from csv file'''
data = []
with open('crime.csv') as file:
lines = csv.reader(file)
next(lines)
for line in lines:
data.append(line)
return data
#list codes and added them to dic
def get_ncic_code_data(data):
ncic_code_list = ['0-999', '1000-1999', '2000-2999', '3000-3999', '4000-4999', '5000-5999', '6000-6999', '7000-7999', '8000-8999']
ncic_code_dict = dict.fromkeys(ncic_code_list)
#loop with dic and ncic code
for x in data:
if int(x[6]) >=0 and int(x[6]) <= 999:
if ncic_code_dict['0-999'] is None:
ncic_code_dict['0-999'] = [x[5]]
else:
ncic_code_dict['0-999'].append(x[5])
elif int(x[6]) >= 1000 and int(x[6]) <= 1999:
if ncic_code_dict['1000-1999'] is None:
ncic_code_dict['1000-1999'] =[x[5]]
else:
ncic_code_dict['1000-1999'].append([x[5]])
elif int(x[6]) >= 2000 and int(x[6]) <= 2999:
if ncic_code_dict['2000-2999'] is None:
ncic_code_dict['2000-2999'] = [x[5]]
else:
ncic_code_dict['2000-2999'].append([x[5]])
elif int(x[6]) >= 3000 and int(x[6]) <=3999:
if ncic_code_dict['3000-3999'] is None:
ncic_code_dict['3000-3999'] = [x[5]]
else:
ncic_code_dict['3000-3999'].append([x[5]])
elif int(x[6]) >= 4000 and int(x[6]) <= 4999:
if ncic_code_dict['4000-4999'] is None:
ncic_code_dict['4000-4999'] = [x[5]]
else:
ncic_code_dict['4000-4999'].append([x[5]])
elif int(x[6]) >= 5000 and int(x[6]) <= 5999:
if ncic_code_dict['5000-5999'] is None:
ncic_code_dict['5000-5999'] = [x[5]]
else:
ncic_code_dict['5000-5999'].append([x[5]])
elif int(x[6]) >= 6000 and int(x[6]) <= 6999:
if ncic_code_dict['6000-6999'] is None:
ncic_code_dict['6000-6999'] = [x[5]]
else:
ncic_code_dict['6000-6999'].append([x[5]])
elif int(x[6]) >= 7000 and int(x[6]) <= 7999:
if ncic_code_dict['7000-7999'] is None:
ncic_code_dict['7000-7999'] = [x[5]]
else:
ncic_code_dict['7000-7999'].append([x[5]])
elif int(x[6]) >= 8000 and int(x[6]) <= 8999:
if ncic_code_dict['8000-8999'] is None:
ncic_code_dict['8000-8999'] = [x[5]]
else:
ncic_code_dict['8000-8999'].append([x[5]])
return ncic_code_dict
#get codes and information
def get_district_data(data):
district_dict = {}
for x in data:
if x[2] in district_dict:
district_dict[x[2]].append(x[5])
else:
district_dict[x[2]] = [x[5]]
return district_dict
def get_beat_data(data):
beat_dict = {}
for x in data:
if x[3].strip() in beat_dict:
beat_dict[x[3].strip()].append(x[5])
else:
beat_dict[x[3].strip()] = [x[5]]
return beat_dict
def get_ncic_list(data):
ncic_list = []
for x in data:
ncic_list.append(x[6])
return ncic_list
def get_count(ncic_code_dict, district_dict, beat_dict):
count_ncic_code_dict = {}
for key in ncic_code_dict:
if ncic_code_dict[key] is None:
count_ncic_code_dict[key] = 0
else:
count_ncic_code_dict[key] = len(ncic_code_dict[key])
count_district_dict = {}
for key in district_dict:
if district_dict[key] is None:
count_district_dict[key] = 0
else:
count_district_dict[key] = len(district_dict[key])
count_beat_dict = {}
for key in beat_dict:
if beat_dict[key] is None:
count_beat_dict[key] = 0
else:
count_beat_dict[key] = len(beat_dict[key])
return count_ncic_code_dict, count_district_dict, count_beat_dict
#create json file
def export_data(count_ncic_code_dict, count_district_dict, count_beat_dict):
'''saves to json file'''
main_list = ['count of crime by ncic code, count of crime by district, count of crime by beat']
main_dict = dict.fromkeys(main_list)
for i in range(len(count_ncic_code_dict)):
for key, value in count_ncic_code_dict.items():
if main_dict['count of crime by ncic code'] is None:
main_dict['count of crime by ncic code'] = {key: value}
else:
main_dict['count of crime by ncic code'].update({key: value})
for i in range(len(count_district_dict)):
for key, value in count_district_dict.items():
if main_dict['count of crime by district'] is None:
main_dict['count of crime by district'] = {key: value}
else:
main_dict['count of crime by district'].update({key: value})
for i in range(len(count_beat_dict)):
for key, value in count_beat_dict.items():
if main_dict['count of crime by beat'] is None:
main_dict['count of crime by beat'] = {key: value}
else:
main_dict['Count of crime by beat'].update({key: value})
with open("October.json", "w") as outfile:
json.dump(main_dict, outfile)
outfile.close()
print("saved information to json file")
#bar graph
def plot_graph(ncic_list_user, count_list, chart_title):
fig, ax = plt.subplots(figsize=(5, 5))
plt.get_current_fig_manager().set_window_title('Crime Bar Graph')
ax.pie(count_list, autopct='%.1f%%')
ax.set_title(chart_title)
plt.legend( loc='right', labels=ncic_list_user)
plt.tight_layout()
fig.savefig('crime.png')
plt.show()
#user display
def main():
data = create_list()
menu='''
Menu:
1. Display Crime Report list that includes NCIC code and by district and by beat:
2. Display all crimes for a beat number.
3. Count of 5 NCIC codes display them and show a bar chart.
4. Quit
'''
print(menu)
selection = input("Enter number from the menu:")
if selection == '1':
'''Display a crime report that will list:
count of crimes by ncic code by 1000 (0-999, 1000-1999, etc) and by district and by beat'''
ncic_code_dict = get_ncic_code_data(data)
district_dict = get_district_data(data)
beat_dict = get_beat_data(data)
count_ncic_code_dict, count_district_dict, count_beat_dict = get_count(ncic_code_dict, district_dict, beat_dict)
print()
export_data(count_ncic_code_dict, count_district_dict, count_beat_dict)
elif selection == '2':
'''Ask the user for a beat number and show all the crimes for that beat'''
print("Beat numbers:")
beat_dict = get_beat_data(data)
for key, value in beat_dict.items():
print (key, end='')
print()
user_input = input("Enter beat number:")
print("Crimes for beat {}: ".format(user_input))
for key, value in beat_dict.items():
if key == user_input:
for val in value:
print(val)
elif selection == '3':
'''Ask user for 5 ncic numbers and create a bar graph
ask the user for a title of the chart and then display the chart'''
ncic_code_dict = get_ncic_code_data(data)
print("Ncic codes:")
ncic_list = get_ncic_list(data)
theset = set(ncic_list)
for x in theset:
print(x, end='')
ncic_list_user = []
print("Enter 5 NCIC codes:")
for i in range(1, 5 1):
user_input = input("Enter NCIC codes #{}: ".format(i))
ncic_list_user.append(user_input)
chart_title = input("Enter chart title:")
count_list = []
for x in ncic_list_user:
count_list.append(ncic_list.count(x))
plot_graph(ncic_list_user, count_list, chart_title)
elif selection == '4':
exit()
main()
uj5u.com熱心網友回復:
匯出資料錯誤
修復匯出回溯的錯誤
Traceback (most recent call last): File "C:\Users\dddst279\My Files\Google Drive\My Drive\Final Project - Deidra Dayak.py", line 254, in <module> main() File "C:\Users\dddst279\My Files\Google Drive\My Drive\Final Project - Deidra Dayak.py", line 203, in main export_data(count_ncic_code_dict, count_district_dict, count_beat_dict) File "C:\Users\dddst279\My Files\Google Drive\My Drive\Final Project - Deidra Dayak.py", line 139, in export_data if main_dict['count of crime by ncic code'] is None: KeyError: 'count of crime by ncic code'
您需要將if main_dict['count of crime by ncic code'] is None:,if main_dict['count of crime by district'] is None:和更改if main_dict['count of crime by beat'] is None:為:
if main_dict.get('count of crime by ncic code') is None:
if main_dict.get('count of crime by district') is None:
if main_dict.get('count of crime by beat') is None:
發生錯誤是因為您試圖訪問一個不存在的密鑰,并且不會回傳任何內容。如果元素可能不存在,則該get()方法是訪問元素鍵的安全方法,如果不存在則回傳 None 。
條形圖
對于條形圖,您需要在呼叫將處理您希望條形圖高度的函式時添加另一個變數。(建議您提供該堆疊跟蹤的錯誤)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/518162.html
上一篇:在Python中讀取和處理RAM有限的多個csv檔案
下一篇:過濾具有串列作為列值的資料框
