1

经过几次操作,我得到了一个模式列表:

[(u'DAY1 KWH', u'300.000000'), 
(u'DAY2 KWH', u'300.000000'), 
(u'DAY3 KWH', u'300.000000'), 
(u'DAY4 KWH', u'300.000000'), 
(u'DAY5 KWH', u'300.000000'), 
(u'DAY6 KWH', u'300.000000'), 
(u'DAY7 KWH', u'300.000000'), 
(u'DAY8 KWH', u'300.000000'), 
(u'DAY9 KWH', u'300.000000'), 
(u'DAY10 KWH', u'300.000000'), 
(u'DAY11 KWH', u'300.000000'), 
(u'DAY12 KWH', u'300.000000'), 
(u'DAY13 KWH', u'300.000000'), 
(u'DAY14 KWH', u'300.000000'),
...

并非所有元素都包含“天”或“千瓦时”这个词——事实上,它们可能是当月天然气使用量或一周用水量等的测量值。我想做的是提取所有“ day”值并将它们放入一个列表中,所有“week”值放入另一个列表中,所有“month”值放入第三个列表中。最终目标是能够绘制每日、每周和每月的公用事业使用情况。请注意,这些是测试值。

我注释掉的五种不同的方法都没有真正起作用,但每次尝试都来自阅读不同的 Stack Overflow 线程。

我知道代码肯定可以变得更高效/更快,所以如果您有任何优化建议,请随时添加。非常感谢您的帮助!

import urllib
import urllib2
from xml.dom import minidom
import matplotlib.pyplot as plt

def main(): 

    path = "http://128.226.6.214/bacrest/bacnet_device_70200/"
    BACrest = 'urn:BACrestService'
    xlink = 'http://www.w3.org/1999/xlink'

    dom = minidom.parse(urllib.urlopen(path)) 

    values = [] 
    descriptions = []
    for node in dom.getElementsByTagNameNS(BACrest, 'ChildNode'):  

        href = node.getAttributeNS(xlink, 'href')

        descriptionDomain = href + '/Description'
        descriptionSubDom = minidom.parse(urllib.urlopen(descriptionDomain))
        descriptionElements = descriptionSubDom.getElementsByTagNameNS(BACrest, 'return')
        descriptions.append(descriptionElements) 

        valueDomain = href + '/Value'
        valueSubDom = minidom.parse(urllib.urlopen(valueDomain))
        valueElements = valueSubDom.getElementsByTagNameNS(BACrest, 'return')[0].firstChild.data
        values.append(valueElements)

    combination = zip(descriptions,values)

解决方案尝试

    #print filter(lambda x: 'DAY1 ' in x, combination)

    #dayInfo = []
    #for sublist in combination:
        #if 'DAY1 ' in sublist:
            #dayInfo.append(sublist)
    #print dayInfo

    #dayInfo = [s for s in combination if 'DAY1 ' in s]
    #print dayInfo

    #dayInfo = [i for i,v in combination if i.startswith('DAY1') in i]
    #print dayInfo

    #dayInfo = []
    #if any('DAY1 ' in x for x in combination):
        #dayInfo.append(x)
    #print dayInfo

main()
4

1 回答 1

0

如您所描述的,如果data是表单的一些列表[(u'DAY1 KWH', u'300.000000'), (u'DAY2 KWH', u'300.000000'), ...],那么以下代码应该可以工作:

for desc, val in data:
    if 'DAY' in desc:
        # do something with val
    elif 'WEEK' in desc:
       # do something else with val
    # etc...

请注意,这并不是特别稳健,因为它会由于大小写等方面的差异而失败。使用正则表达式匹配,或者desc在执行字符串搜索之前在每次迭代中向上转换,可能会非常优越,除非您可以绝对确定输入将始终为大写。

于 2012-06-03T04:43:46.920 回答