【问题标题】:Analyzing cumbersome information分析繁琐的信息
【发布时间】:2014-12-18 08:12:08
【问题描述】:

我正在为我的朋友和我创建一个交互式成绩簿环境。到目前为止,我已经能够使用我的脚本、下载我的成绩并过滤哪些信息是重要的。我的脚本如下。

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%)。

【问题讨论】:

  • 你的标题读起来像垃圾邮件。
  • 那么您的问题到底是什么?到目前为止,您尝试提取什么数字?

标签: python string list python-2.7


【解决方案1】:

您必须提取成绩信息;你没有具体说明数字的含义,所以我猜它们被称为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 并加上 % 字符)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 2011-02-11
    • 2012-01-30
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多