1

我已经使用此代码以这种方式打印了一个内容。此代码打印出所有内容,如何使用 IF 打印特定位置?比如上武吉知马、西海岸……

地区:上武吉知马摘要:多云纬度:1.356084 经度:103.768873

地区:西海岸摘要:多云纬度:1.30039493 经度:103.7504196

地区:林地概要:多云纬度:1.44043052 经度:103.7878418

地区:义顺 概况:多云 纬度:1.42738834 经度:103.8290405

import urllib2
from BeautifulSoup import BeautifulStoneSoup #Using bs3


url="https://api.projectnimbus.org/neaodataservice.svc/NowcastSet"
request = urllib2.Request(url)
request.add_header("accept", "*/*")
request.add_header('AccountKey', "OSJeROQjTg4v7Ec3kiecjw==")
request.add_header('UniqueUserID', "00000000000000000000000000000001")
result = urllib2.urlopen(request)
xml_str = result.read()

soup = BeautifulStoneSoup(xml_str)

prop_list = []
for content in soup.findAll("m:properties"):
    props = {}
    for prop in content.findChildren():
        props[prop.name[2:]] = prop.text
    prop_list.append(props)


for prop in sorted(prop_list):
    print "Area: %(area)s\nSummary: %(summary)s\nLatitude: %(latitude)s\nLongitude: %(longitude)s\n" % prop
4

2 回答 2

0
for prop in sorted(prop_list):
    if (prop["area"] == "whatever u wnt or someother condition"):
        print "Area: %(area)s\nSummary: %(summary)s\nLatitude: %(latitude)s\nLongitude: %(longitude)s\n" % prop  
于 2013-07-15T10:01:52.453 回答
0

好吧,您必须if在最终for循环中添加一条语句,检查当前条目是否在某个肯定列表中。像这样的东西:

areas_to_print = ["Upper Bukit Timah", "West Coast", "Woodlands", "Yishun"]

for prop in sorted(prop_list):
    if prop["area"] in areas_to_print:
        print "Area: %(area)s\nSummary: %(summary)s\nLatitude: %(latitude)s\nLongitude: %(longitude)s\n" % prop

或者,您也可以将相同if的语句添加到您的第一个for循环中,这样一开始只有这些条目被添加到prop_list

于 2013-07-15T09:57:44.313 回答