从列表元素

时间:2017-05-07 12:58:00

标签: python-3.x function class

我不确定标题是否准确描述了我正在尝试做的事情。我有一个我编写的Python3.x脚本,当我家附近的河流达到最低洪水阶段时,它将向我的Facebook页面发出洪水警告。现在脚本工作,但它只报告来自一个测量站的数据。我希望能够处理来自我所在县的所有站点的数据(共5个),所以我想也许一个类方法可以做到这一点,但我不确定如何实现它。我从1月份开始自学Python,并且对大部分语言感到非常自在,虽然我对如何构建类对象有很好的了解,但我不确定我的流程图应该如何。现在是代码:

#!/usr/bin/env python3

''' 
Facebook Flood Warning Alert System - this script will post a notification to
to Facebook whenever the Sabine River @ Hawkins reaches flood stage (22.3') 
'''

import requests
import facebook
from lxml import html

graph = facebook.GraphAPI(access_token='My_Access_Token') 

river_url = 'http://water.weather.gov/ahps2/river.php?wfo=SHV&wfoid=18715&riverid=203413&pt%5B%5D=147710&allpoints=143204%2C147710%2C141425%2C144668%2C141750%2C141658%2C141942%2C143491%2C144810%2C143165%2C145368&data%5B%5D=obs'

ref_url = 'http://water.weather.gov/ahps2/river.php?wfo=SHV&wfoid=18715&riverid=203413&pt%5B%5D=147710&allpoints=143204%2C147710%2C141425%2C144668%2C141750%2C141658%2C141942%2C143491%2C144810%2C143165%2C145368&data%5B%5D=all'

def checkflood():
    r = requests.get(river_url)
    tree = html.fromstring(r.content)
    stage = ''.join(tree.xpath('//div[@class="stage_stage_flow"]//text()'))
    warn = ''.join(tree.xpath('//div[@class="current_warns_statmnts_ads"]/text()'))
    stage_l = stage.split()
    level = float(stage_l[2])

    #check if we're at flood level
    if level < 22.5:
        pass
    elif level == 37:
        major_diff = level - 23.0
        major_r = ('The Sabine River near Hawkins, Tx has reached [Major Flood Stage]: @', stage_l[2], 'Ft. ', str(round(major_diff, 2)), ' Ft. \n Please click the link for more information.\n\n Current Warnings and Alerts:\n ', warn)
        major_p = ''.join(major_r)
        graph.put_object(parent_object='me', connection_name='feed', message = major_p, link = ref_url)
    <--snip-->

checkflood()

每个站点有不同的5种不同类型的洪水阶段:行动,洪水,中等,重要,每个站点的每个不同深度。所以对霍金斯的萨宾河而言,它将是行动 - 22',洪水 - 24',中等 - 28',少校 - 32'。对于其他statinos,那些深度是不同的。所以我知道我必须从以下内容开始:

class River:
    def __init__(self, id, stage):
    self.id = id #station ID
    self.stage = stage #river level'

    @staticmethod
    def check_flood(stage):
        if stage < 22.5:
          pass
        elif stage.....

但从那里我不知道该怎么做。它应该添加到(到?)代码中,我是否应该编写一个类来处理Facebook帖子,这是否需要一个类方法来处理,有没有办法清理它以提高效率?我不是在寻找任何人为我写这篇文章,但一些提示和指示肯定会有所帮助。谢谢大家!

编辑以下是我发现并正在运作的内容:

class River:
    name = ""
    stage = ""
    action = ""
    flood = ""
    mod = ""
    major = ""
    warn = ""

    def checkflood(self):
        if float(self.stage) < float(self.action):
            pass
        elif float(self.stage) >= float(self.major):
             <--snip-->

mineola = River()
mineola.name = stations[0]
mineola.stage = stages[0]
mineola.action = "13.5"
mineola.flood = "14.0"
mineola.mod = "18.0"
mineola.major = "21.0"
mineola.alert = warn[0]

hawkins = River()
hawkins.name = stations[1]
hawkins.stage = stages[1]
hawkins.action = "22.5"
hawkins.flood = "23.0"
hawkins.mod = "32.0"
hawkins.major = "37.0"
hawkins.alert = warn[1]

<--snip-->

所以从这里开始,我要把所有单独的河块都塞进一个街区。到目前为止我所尝试的是:

class River:
...     name = ""
...     stage = ""
...     def testcheck(self):
...        return self.name, self.stage
... 
>>> for n in range(num_river):
...     stations[n] = River()
...     stations[n].name = stations[n]
...     stations[n].stage = stages[n]
... 
>>> for n in range(num_river):
...     stations[n].testcheck()
... 
<__main__.River object at 0x7fbea469bc50> 4.13
<__main__.River object at 0x7fbea46b4748> 20.76
<__main__.River object at 0x7fbea46b4320> 22.13
<__main__.River object at 0x7fbea46b4898> 16.08

所以这并没有给我打印出我期待的结果。如何返回字符串而不是对象?我能以这种方式定义类变量,还是必须单独列出它们?再次感谢!

1 个答案:

答案 0 :(得分:0)

在阅读了manymanymany关于类对象的文章和教程后,我能够找到使用列表创建对象的解决方案元素。

class River():
   def __init__(self, river, stage, flood, action):
       self.river = river
       self.stage = stage
       self.action = action
       self.flood = flood
       self.action = action

   def alerts(self):
       if float(self.stage < self.flood):
           #alert = "The %s is below Flood Stage (%sFt) @ %s Ft. \n" % (self.river, self.flood, self.stage)
           pass
       elif float(self.stage > self.flood):
           alert = "The %s has reached Flood Stage(%sFt) @ %sFt. Warnings: %s \n" % (self.river, self.flood, self.stage, self.action)
           return alert

'''this is the function that I was trying to create
   to build the class objects automagically'''

def riverlist(): 
    river_list = []
    for n in range(len(rivers)):
        station = River(river[n], stages[n], floods[n], warns[n])
        river_list.append(station)
    return river_list

if __name__ == '__main__':
    for x in riverlist():
        print(x.alerts())