讨论/综合讨论/求大神优化代码/
求大神优化代码

-----Statement of Authorship-----

This is an individual assessment item. By submitting this code I agree that it represents my own work.
Student no: PUT YOUR STUDENT NUMBER HERE
Student name: PUT YOUR NAME HERE

NB: Files submitted without a completed copy of this statement will not be marked. All files submitted will be subjected to software plagiarism analysis using the MoSS system.(http://theory.stanford.edu/~aiken/moss/).

-----Task Description-----

POPULARITY CLOUDS Movie fans have strong opinions about their favourite actors. In this task you will develop a program that helps visualise some of the opinions of movie fans derived from a survey of Microsoft employees. To do so you will make use of three different computer languages, Python, SQLite and HTML. You will develop a Python function, show popularity, which accesses data in an SQL database and uses this to generate HTML documents which visually display an actor's popularity according to the survey results. See the instructions accompanying this file for full details.

-----Acceptance Tests-----

This section contains unit tests that run your program. You may not change anything in this section. NB: 'Passing' these tests does NOT mean you have completed the assignment because they do not check the HTML files produced by your program.

-----Normal Cases with valid input-----

show_popularity(['Female', 'Male', '30-40'], 20, 'Test01') # Test 1

show_popularity(['20-30', '30-40', '40-50'], 50, 'Test02') # Test 2

show_popularity(['20-40', '40-80', 'All'], 30, 'Test03') # Test 3

show_popularity(['Female', 'Male', '30-40', '40-60', '60-100', 'All'], 30, 'Test04') # Test 4

show_popularity(['All'], 20, 'Test05') # Test 5

show_popularity(['30-40'], 50, 'Test06') # Test 6

show_popularity(['30-50'], 0, 'Test07') # Test 7

-----Cases with invalid input-----

show_popularity(['20-30', '30-40', '3a-34' ], 30, 'Test08') # Test 8
Invalid customer group: 3a-34

show_popularity(['teens', '20-20','30-40','40-50', '50-50', '60-d0'], 30, 'Test09') # Test 9
Invalid customer group: teens
Invalid customer group: 60-d0

show_popularity(['old people', '30', '40-60', '-70', '70-100'], 30, 'Test10') # Test 10
Invalid customer group: old people
Invalid customer group: 30
Invalid customer group: -70

show_popularity(['-', '30-50', '40-60', '50-20', '40 60'], 50, 'Test11') # Test 11
Invalid customer group: -
Invalid customer group: 40 60

show_popularity(['9-20'], 50, 'TestX')

-----Students' Solution-----

Complete the task by filling in the template below.
Get the sql functions
import sqlite3
获得正则表达式
from re import findall
在网页中显示结果的 函数
import webbrowser

PUT YOUR show_popularity FUNCTION HERE
主体函数

def show_popularity(limit_datas,shown_number,output_name):
#遍历限制条件
for number in range(len(limit_datas)):
#step1:从数据库中获得相应数据
output_list=read_in_sql(limit_datas[number])
#若输入有误则进入下一次循环
if output_list==1:
continue
#step2:处理数据,得到要显示的数据
final_data=data_computing(output_list,shown_number)
#读取有效数据条数
count=0
for number1 in range(len(final_data)):
count+=final_data[number][1]
#判断页面位置 此处有个问题,如果第一个和最后一个数据不符合要求就会没有头尾页面,以及页面间的连接也需要额外的参数,所以主函数不能简单地遍历,需要重构先简单地拿这个把三号函数写完吧
page_situation=1
if number==0:
page_situation=0
elif number==len(limit_datas)-1:
page_situation=2
#step3:构建网页
html_priting(shown_number,limit_datas[number],output_name,count,final_data,page_situation)

读取数据函数 Z

def read_in_sql(input_data):
#连接到SQLite数据库
conn=sqlite3.connect('movie_survey.db')
cursor=conn.cursor()
#正则表达式判断范围
if input_data=='All':
#第一种情况:选取所有数据
cursor.execute('''SELECT actor FROM favorite_actors''')#在数据库中找出符合范围的所需数据
return cursor.fetchall()
elif input_data=='Male':
#第二种情况:只选取男性
cursor.execute('''select actor from favorite_actors,customers
WHERE favorite_actors.customerID=customers.customerID
AND customers.gender="Male"''')#在数据库中找出符合范围的所需数据
return cursor.fetchall()
elif input_data=='Female':
#第三种情况:只选取女性
cursor.execute('''select actor from favorite_actors,customers
WHERE favorite_actors.customerID=customers.customerID
AND customers.gender="Female"''')#在数据库中找出符合范围的所需数据
return cursor.fetchall()
elif findall('[0-9]+-[0-9]+',input_data)!=[]:
#第四种情况:输入年龄段选取符合要求的年龄群体
age_range=findall('[0-9]+',input_data) #正则表达式确定查找范围
cursor.execute('''select actor from favorite_actors,customers
WHERE favorite_actors.customerID=customers.customerID
AND customers.age BETWEEN '''+age_range[0]+' and '+age_range[1])#在数据库中找出符合范围的所需数据
return cursor.fetchall()
else:
#default情况:输入非法,报错返回
print('Invalid customer group: '+input_data)
return 1
#关闭数据库
cursor.close()
conn.close()

处理数据函数
注:input_number 不知道为啥是二维列表....由演员名 +None 组成,需注意

def data_computing(input_list,shown_number):
#将列表处理为演员名—喜爱人数的二维数组
pure_list=[] #pure_list为第一步处理所得列表,不限制数据数量
for actor in input_list:
flag=0
for i in range(len(pure_list)):
if actor[0]==pure_list[i][0]:
pure_list[i][1]+=1
flag=1
break
if flag==0:
pure_list.append([actor[0],1])
#根据喜爱人数多少从大到小重新排列
pure_list.sort(key=(lambda x:x[1]),reverse=True)
#根据所需数量截得到最终所需数组
result_list=[]
for number in range(shown_number):
if number>=len(pure_list):
break
result_list.append(pure_list[number])
return result_list
#在列表中加入颜色

打印网页函数
注:网页所需数据 显示数量、限制条件、有效信息条数、处理函数传入的结果数组、首尾页信息

def html_priting(shown_number,limit_data,output_name,num_count,result_list,page_situation):
#命名生成的html
GEN_HTML = output_name+"_"+limit_data+".html"
#打开文件,准备写入
f = open(GEN_HTML,'w')

#准备相关变量
str1 = 'test_message'

#HTML内容
message = """
<html>
<head></head>
<body>
<h1 style="text-align:center">Top %s Most Popular Actors</h1>
<p style="text-align:center;font-size:20px;margin:0;font-weight:bold">Customer Group: %s</p>
<p style="text-align:center;font-size:20px;margin:0;font-weight:bold">Number of Customers: %s</p>
<hr></hr>
<p style="text-align:center;margin:0;font-weight:bold">%s</p>
<hr></hr>
</body>
</html>"""%(shown_number,limit_data,num_count,str1)

#写入文件
f.write(message)
#关闭文件
f.close()

#运行完自动在网页中显示
webbrowser.open(GEN_HTML,new = 1)

-----Automatic Testing-----

The following code will automatically run the unit tests
when this program is "run". Do not change anything in this
section. If you want to prevent the tests from running, comment
out the code below, but ensure that the code is uncommented when
you submit your program.

if name == "main":
from doctest import testmod
testmod(verbose=True)

下面是需要的效果图
屏幕快照 2019-11-22 上午1.19.18.png

展开讨论
共 0 个讨论
无讨论