用python实现九型人格测试,并把测试结果绘制成饼图,实现代码如下:
# @Description: 九型人格 import xlrd, matplotlib.pyplot as plt data = xlrd.open_workbook(r'E:python_script ine.xlsx') table = data.sheets()[0] checkout = []#存储题号 labs = [] #存储九种性格 sizes = [] #存储大小 explode=[0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05]#每块之间的间隙 with open('ninp.txt', encoding='utf-8') as f: f.seek(0) rule = eval(f.read()) f.close() for i in range(table.nrows): if table.row_values(i)[2] == 1: # 如果选中的是1 则把题号存入checkout checkout.append(int(table.row_values(i)[0])) for i in checkout: for j in rule: if i in rule[j]['QNO']: # 如果题号在规则中,则size +1 rule[j]['size'] += 1 for x in rule: labs.append(x) sizes.append(rule[x]['size']) plt.figure(figsize=(12,6)) plt.title("My Test Result ") colors=['lightgreen','gold','lightskyblue','lightcoral','red','blue','yellow','darkgreen','purple'] plt.pie(sizes,explode=explode,labels=labs,colors=colors, labeldistance=1.1,autopct='%3.1f%%',shadow = False, startangle=90,pctdistance=0.6) plt.axis('equal') plt.legend() plt.show()
运行结果如下:
ninp.txt里存储的规则字典格式如下:
{ "Perfect":{'QNO':[2,14,55,57,60,63,73,81,87,91,97,102,104,106],'size':0}, "Helping":{'QNO':[6,8,22,30,69,71,79,82,85,86,89,90],'size':0}, "Achievement":{'QNO':[20,33,38,59,65,67,70,72,74,77,80,93],'size':0}, "Ego":{'QNO':[7,13,17,52,53,54,56,58,61,64,100,105],'size':0}, "Observation":{'QNO':[3,19,23,32,42,43,47,48,51,83,88,99,101],'size':0}, "Loyal":{'QNO':[9,10,26,29,31,35,37,45,46,68,75],'size':0}, "Hedonism":{'QNO':[4,16,18,21,28,49,78,92,103],'size':0}, "Leading":{'QNO':[5,11,24,27,40,44,50,66,76,84,95,96],'size':0}, "Peace":{'QNO':[1,12,15,25,34,36,39,41,62,94,98,107,108],'size':0} }
nine.xlsx文件题目及测试结果内容如下: