我正在为我的朋友和我创建一个互动成绩簿环境。到目前为止,我已经能够使用我的脚本,下载我的成绩,以及过滤哪些信息很重要。我的脚本如下:
import requests
from bs4 import BeautifulSoup
# Connect to D2L
s = requests.Session()
payload = {
'd2l_referrer': '',
'target': '/d2l/lp/ouHome/loginHome.d2l?isMobile=1',
'loginPath': '/d2l/m/login',
'userName': 'USERNAME',
'password': 'PASSWORD'
}
r = s.post('http://learn.ou.edu/d2l/lp/auth/login/login.d2l', data=payload)
status = r.status_code
if status == 200:
print "Connection Successful"
else:
print "Unable to connect"
# Grade Collection
print " Getting CLASS grades..."
page = s.get("GRADEBOOK URL")
soup = BeautifulSoup(page.content)
grade = BeautifulSoup(str(soup.find_all('label')))
for strings in grade.stripped_strings:
if "/" in strings:
print strings
print "Complete"
脚本返回:
Connection Successful
Getting CLASS grades...
50 / 50
40 / 50
40 / 50
45 / 50
50 / 50
Complete
此时,我希望程序在" /"两侧的数字总和?并划分总数,从而给出"平均值"。防爆。 ((50+40+40+45+50)/(50+50+50+50+50)) = 0.9
或(90%
)。
答案 0 :(得分:2)
您必须提取成绩信息;你没有说明数字的含义,所以我猜它们被称为passed
和total
:
passed = totals = 0
for strings in grade.stripped_strings:
if "/" in strings:
print strings
pass_, total = map(float, strings.split('/'))
passed += pass_
totals += total
print "The average is: {:.1%}".format(passed / totals)
演示:
>>> lines = '''\
... 50 / 50
... 40 / 50
... 40 / 50
... 45 / 50
... 50 / 50
... '''
>>> for strings in lines.splitlines():
... if "/" in strings:
... print strings
... pass_, total = map(float, strings.split('/'))
... passed += pass_
... totals += total
...
50 / 50
40 / 50
40 / 50
45 / 50
50 / 50
>>> print "The average is: {:.1%}".format(passed / totals)
The average is: 90.0%
.1%
格式指令将浮点数格式化为1个小数点的百分比(乘以100并添加%
字符)。