我使用此代码以这种方式打印了一个内容。此代码打印出所有内容,如何使用IF打印特定位置?如Upper Bukit Timah,西海岸...
地区:武吉知马上段 摘要:多云 纬度: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
答案 0 :(得分: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
。
答案 1 :(得分: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