绘制经典

[In ]:
from datascience import *
from datascience.predicates import are
path_data = '../../../../data/'
import numpy as np
import matplotlib
matplotlib.use('Agg')
%matplotlib inline
import matplotlib.pyplot as plots
plots.style.use('fivethirtyeight')
import warnings
warnings.simplefilter(action="ignore", category=FutureWarning)

from urllib.request import urlopen 
import re
def read_url(url): 
    return re.sub('\\s+', ' ', urlopen(url).read().decode())

在这个示例中,我们将探索两部经典小说的统计数据:马克·吐温的《哈克贝利·费恩历险记》和路易莎·梅·奥尔科特的《小妇人》。任何书籍的文本都可以由计算机高速读取。1923年之前出版的书籍目前处于公有领域,意味着每个人都有权以任何方式复制或使用这些文本。古腾堡计划是一个在线发布公有领域图书的网站。使用 Python,我们可以直接从网页加载这些书籍的文本。

这个示例旨在说明本书的一些广泛主题。如果程序的细节暂时难以理解,不必担心。相反,请专注于解读下方生成的图像。本书后续章节将介绍下面使用的 Python 编程语言的大部分特性。

首先,我们将两本书的文本读入章节列表中,分别命名为 huck_finn_chapterslittle_women_chapters。在 Python 中,名称不能包含空格,因此我们经常使用下划线 _ 来代替空格。下面代码行中的 = 将左侧的名称绑定到右侧计算结果。统一资源定位符(URL) 是互联网上某些内容的地址;在本例中,是书籍的文本。# 符号表示注释,会被计算机忽略,但对阅读代码的人很有帮助。

[In ]:
# Read two books, fast!

huck_finn_url = 'https://www.inferentialthinking.com/data/huck_finn.txt'
huck_finn_text = read_url(huck_finn_url)
huck_finn_chapters = huck_finn_text.split('CHAPTER ')[44:]

little_women_url = 'https://www.inferentialthinking.com/data/little_women.txt'
little_women_text = read_url(little_women_url)
little_women_chapters = little_women_text.split('CHAPTER ')[1:]

虽然计算机无法理解书籍的文本,但它可以为我们提供文本结构方面的一些洞察。huck_finn_chapters 这个名称当前绑定到书中所有章节的列表。我们可以将它们放入表格中,查看每章的开头。

[In ]:
# Display the chapters of Huckleberry Finn in a table.

Table().with_column('Chapters', huck_finn_chapters)
Chapters
I. YOU don't know about me without you have read a book  ...
II. WE went tiptoeing along a path amongst the trees bac ...
III. WELL, I got a good going-over in the morning from o ...
IV. WELL, three or four months run along, and it was wel ...
V. I had shut the door to. Then I turned around and ther ...
VI. WELL, pretty soon the old man was up and around agai ...
VII. "GIT up! What you 'bout?" I opened my eyes and look ...
VIII. THE sun was up so high when I waked that I judged  ...
IX. I wanted to go and look at a place right about the m ...
X. AFTER breakfast I wanted to talk about the dead man a ...
... (33 rows omitted)

每章以罗马数字的章节编号开头,随后是章节的第一句话。古腾堡计划将每章的第一个单词以大写形式印刷。