使用内置的urlparse module,不要自己做这些分裂。
>>> import urlparse
>>> url_to_parse = "http://example.com/servlet/charting?base_color=grey&chart_width=288&chart_height=160&chart_type=png&chart_style=manufund_pie&3DSet=true&chart_size=small&leg_on=left&static_xvalues=10.21,12.12,43.12,12.10,&static_labels=blue,red,green,purple"
>>> parsed_url = urlparse.urlparse(url_to_parse)
>>> query_as_dict = urlparse.parse_qs(parsed_url.query)
>>> print query_as_dict
{'chart_size': ['small'], 'base_color': ['grey'], 'chart_style': ['manufund_pie'], 'chart_height': ['160'], 'static_xvalues': ['10.21,12.12,43.12,12.10,'], 'chart_width': ['288'], 'static_labels': ['blue,red,green,purple'], 'leg_on': ['left'], 'chart_type': ['png'], '3DSet': ['true']}
如果您使用的Python版本低于2.6,那么您必须导入cgi module。做到这一点,而不是:
>>> import urlparse
>>> import cgi
>>> parsed_url = urlparse.urlparse(url_to_parse)
>>> query_as_dict = cgi.parse_qs(parsed_url.query)
>>> print query_as_dict
{'chart_size': ['small'], 'base_color': ['grey'], 'chart_style': ['manufund_pie'], 'chart_height': ['160'], 'static_xvalues': ['10.21,12.12,43.12,12.10,'], 'chart_width': ['288'], 'static_labels': ['blue,red,green,purple'], 'leg_on': ['left'], 'chart_type': ['png'], '3DSet': ['true']}
然后将它们关联到字典,使用所提供的字典构造一起zip。
>>> print dict(zip(query_as_dict['static_labels'][0].split(','), query_as_dict['static_xvalues'][0].split(',')))
{'blue': '10.21', 'purple': '12.10', 'green': '43.12', 'red': '12.12'}
这不是文字,而是HTML。标题和标签已调整。 – 2011-03-14 08:54:55