这个练习的目标是生成一个图表作为该页面中的特定部分:(http://www.realclearpolitics.com/epolls/2012/president/us/general_election_romney_vs_obama-1171.html)我不能明白的代码
用于生成这样的图上的数据被存储为XML页,网址如: http://charts.realclearpolitics.com/charts/[id].xml 这里,[id]是一个唯一的整数,位于显示图形的页面的URL的末尾。奥巴马,罗姆尼的比赛ID是1171:
import re
def get_poll_xml(poll_id):
url ="http://charts.realclearpolitics.com/charts/%i.xml" %int(poll_id)
return requests.get(url).text
def _strip(s): # function to remove characters
return re.sub(r'[\W_]+', '', s)
def plot_colors(xml):
'''
Given an XML document like the link above, returns a python dictionary
that maps a graph title to a graph color.
Both the title and color are parsed from attributes of the <graph> tag:
<graph title="the title", color="#ff0000"> -> {'the title': '#ff0000'}
'''
dom = web.Element(xml)
result = {}
for graph in dom.by_tag('graph'):
title = _strip(graph.attributes['title'])
result[title] = graph.attributes['color']
return result
def rcp_poll_data(xml):
"""
A pandas DataFrame with the following columns:
date: The date for each entry
title_n: The data value for the gid=n graph
This DataFrame should be sorted by date
Example
-------
Consider the following simple xml page:
<chart>
<series>
<value xid="0">1/27/2009</value>
<value xid="1">1/28/2009</value>
</series>
<graphs>
<graph gid="1" color="#000000" balloon_color="#000000" title="Approve">
<value xid="0">63.3</value>
<value xid="1">63.3</value>
</graph>
<graph gid="2" color="#FF0000" balloon_color="#FF0000" title="Disapprove">
<value xid="0">20.0</value>
<value xid="1">20.0</value>
</graph>
</graphs>
</chart>
Given this string, rcp_poll_data should return
result = pd.DataFrame({'date': pd.to_datetime(['1/27/2009', '1/28/2009']),
'Approve': [63.3, 63.3], 'Disapprove': [20.0, 20.0]})
"""
dom = web.Element(xml)
result = {}
dates = dom.by_tag('series')[0]
dates = {n.attributes['xid']: str(n.content) for n in dates.by_tag('value')}
keys = dates.keys()
result['date'] = pd.to_datetime([dates[k] for k in keys])
for graph in dom.by_tag('graph'):
name = graph.attributes['title']
data = {n.attributes['xid']: float(n.content) if n.content else np.nan for n in graph.by_tag('value') }
keyl = data.keys()
result[name] = [data[k]for k in keyl]
result = pd.DataFrame(result)
result = result.sort(columns=['date'])
return result
def poll_plot(poll_id):
xml = get_poll_xml(poll_id)
data = rcp_poll_data(xml)
colors = plot_colors(xml)
#remove characters like apostrophes
data = data.rename(columns = {c: _strip(c) for c in data.columns})
#normalize poll numbers so they add to 100%
norm = data[colors.keys()].sum(axis=1)/100
for c in colors.keys():
data[c] /= norm
for label, color in colors.items():
plt.plot(data.date, data[label], color=color, label=label)
plt.xticks(rotation=70)
plt.legend(loc='best')
plt.xlabel("Date")
plt.ylabel("Normalized Poll Percentage")
poll_plot(1044)
plt.title("Obama Job Approval")
在上述代码中,我不可能了解以下部分,可有人给我解释一下。我完全失去了。
data = data.rename(columns = {c: _strip(c) for c in data.columns})
#normalize poll numbers so they add to 100%
norm = data[colors.keys()].sum(axis=1)/100
for c in colors.keys():
data[c] /= norm
for label, color in colors.items():
plt.plot(data.date, data[label], color=color, label=label)
我认为之前有人从事过它。也许这篇文章可能会帮助你http://stackoverflow.com/questions/19343016/parse-through-an-xml-in-python – 2014-09-26 03:28:39
不,但它不能解决我的问题。我无法理解我的代码的某个部分。但解析的例子完全不同 – MJP 2014-09-26 03:31:17
“你能为我解释这个代码吗”并不是一个好的SO问题。我们需要听听为什么你不理解它,尤其是你不了解的,也许更重要的是你为什么*拥有你所不了解的所有代码。 :)我的意思是,你遇到麻烦的代码对我来说看起来并不复杂,其余的你没有问题... – 2014-09-26 04:16:24