Python编程:从入门到实践 第17章课后习题
本章节关于可视化pygal的设置,有一句需要调整,原文是:
my_style = LS('#336699', base_style=LCS)
应该调整一下(可能是因为pygal更新了)
my_style = LS(colors=('#336699',), base_style=LCS)
17-1 其他语言:修改python_repos.py中的API调用,使其在生成的图表中显示使用其他语言编写的最受欢迎的项目。请尝试语言JavaScript、Ruby、C、Java、Perl、 Haskell和Go等。
C语言第一名是。。。linux,前十名还有redis,git……这,到底是老大……
我还是觉得pyplot好用一些,所以没有按照教材用pygal。
import requests
import matplotlib.pyplot as plt
def get_data(language):
url = "https://api.github.com/search/repositories?q=language:" \
+ language + "&sort=stars"
r = requests.get(url)
response_dict = r.json()
repo_dicts = response_dict["items"]
# 这几句可以不要,但不要就看不到每个dict的字段名称。
# sample_item = repo_dicts[0]
# for k in sample_item:
# print(k)
names, stars, create_dates = [], [], []
for repo_dict in repo_dicts:
names.append(repo_dict['name'])
stars.append(repo_dict['stargazers_count'])
date = str(repo_dict['created_at']) # 注1
create_dates.append(date[0:10])
return names, stars, create_dates
def plot_data(create_dates, language, names, stars):
fig, ax = plt.subplots(figsize=(12, 9))
ax.scatter(names[:10], stars[:10])
# 在每个点上标记一下创建的日期
for i, txt in enumerate(create_dates):
ax.annotate(txt, (names[i], stars[i]))
ax.set(title="10 Most starred repo of " + str(language) + " on github",
xlabel="repo name", ylabel="stars")
ax.tick_params(axis="x", rotation=45)
plt.show()
languages = ["JavaScript", "Ruby", "C"]
for language in languages:
names, stars, create_dates = get_data(language)
plot_data(create_dates, language, names, stars)
注1:github上的created at时间是2011-09-04T22:48:12Z
样式,我StackOverflow上搜索了一下把后面时间去掉的方法:Display Python datetime without time - Stack Overflow,发现不太行,时间原因没仔细看是因为我的时间格式有T和Z,还是因为我写的不对。
于是就想到把这个玩意先转换成字符串,然后截取0-9位就行了。
17-2 最活跃的讨论:使用hn_submissions.py中的数据,创建一个条形图,显示Hacker News上当前最活跃的讨论。条形的高度应对应于文章得到的评论数量,条形的标 签应包含文章的标题,而每个条形应是到该文章讨论页面的链接。
打不开这个hn_submissions.py中的api链接,囧了。。
略吧……
17-3 测试python_repos.py:在python_repos.py中,打印status_code的值,以核实API调用是否成功了。请编写一个名为test_python_repos.py的程序,它使用单元测试来断言status_code 的值为200。想想你还可做出哪些断言,如返回的条目数符合预期,仓库总数超过特定的值等。
import unittest
import requests
def get_status_code():
url = "https://api.github.com/search/repositories?q=language:c&sort=stars"
r = requests.get(url)
status = r.status_code
return status
class StatusCodeTest(unittest.TestCase):
def test_status_code(self):
code = get_status_code()
self.assertEqual(code, 200)
if __name__ == "main":
unittest