├── LICENSE
├── README.md
└── ThePythonApprentice_Code
├── Chapter01
├── help_math_factorial.repl
├── math_module_help.repl
├── start_repl_linux.repl
├── start_repl_osx.repl
├── start_repl_windows.repl
└── zen_of_python.repl
├── Chapter02
└── str-help.txt
├── Chapter03
├── docstrings.repl
├── docstrings2.repl
├── import_words.repl
├── main_index_error.repl
├── words.1.py
├── words.2.py
├── words.3.main.py
├── words.3.py
├── words.4.py
├── words.5.py
├── words.6.py
└── words.7.py
└── README.txt
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 Packt
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | # The-Python-Apprentice
5 | The Python Apprentice, published by Packt
6 | ### Download a free PDF
7 |
8 | If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost.
Simply click on the link to claim your free PDF.
9 |
https://packt.link/free-ebook/9781788293181
--------------------------------------------------------------------------------
/ThePythonApprentice_Code/Chapter01/help_math_factorial.repl:
--------------------------------------------------------------------------------
1 | >>> help(math.factorial)
2 | Help on built-in function factorial in module math:
3 |
4 | factorial(...)
5 | factorial(x) -> Integral
6 |
7 | Find x!. Raise a ValueError if x is negative or non-integral.
--------------------------------------------------------------------------------
/ThePythonApprentice_Code/Chapter01/math_module_help.repl:
--------------------------------------------------------------------------------
1 | >>> help(math)
2 | Help on module math:
3 |
4 | NAME
5 | math
6 |
7 | MODULE REFERENCE
8 | http://docs.python.org/3.3/library/math
9 |
10 | The following documentation is automatically generated from the Python
11 | source files. It may be incomplete, incorrect or include features that
12 | are considered implementation detail and may vary between Python
13 | implementations. When in doubt, consult the module reference at the
14 | location listed above.
15 |
16 | DESCRIPTION
17 | This module is always available. It provides access to the
18 | mathematical functions defined by the C standard.
19 |
20 | FUNCTIONS
21 | acos(...)
22 | acos(x)
23 |
24 | Return the arc cosine (measured in radians) of x.
--------------------------------------------------------------------------------
/ThePythonApprentice_Code/Chapter01/start_repl_linux.repl:
--------------------------------------------------------------------------------
1 | $ python3.5
2 | Python 3.5.0+ (default, Oct 11 2015, 09:05:38)
3 | [GCC 5.2.1 20151010] on linux
4 | Type "help", "copyright", "credits" or "license" for more information.
5 | >>>
6 |
--------------------------------------------------------------------------------
/ThePythonApprentice_Code/Chapter01/start_repl_osx.repl:
--------------------------------------------------------------------------------
1 | > python
2 | Python 3.5.0 (default, Nov 3 2015, 13:17:02)
3 | [GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
4 | Type "help", "copyright", "credits" or "license" for more information.
5 | >>>
6 |
--------------------------------------------------------------------------------
/ThePythonApprentice_Code/Chapter01/start_repl_windows.repl:
--------------------------------------------------------------------------------
1 | > python
2 | Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AMD64)] on win32
3 | Type "help", "copyright", "credits" or "license" for more information.
4 | >>>
--------------------------------------------------------------------------------
/ThePythonApprentice_Code/Chapter01/zen_of_python.repl:
--------------------------------------------------------------------------------
1 | >>> import this
2 | The Zen of Python, by Tim Peters
3 |
4 | Beautiful is better than ugly.
5 | Explicit is better than implicit.
6 | Simple is better than complex.
7 | Complex is better than complicated.
8 | Flat is better than nested.
9 | Sparse is better than dense.
10 | Readability counts.
11 | Special cases aren't special enough to break the rules.
12 | Although practicality beats purity.
13 | Errors should never pass silently.
14 | Unless explicitly silenced.
15 | In the face of ambiguity, refuse the temptation to guess.
16 | There should be one-- and preferably only one --obvious way to do it.
17 | Although that way may not be obvious at first unless you're Dutch.
18 | Now is better than never.
19 | Although never is often better than *right* now.
20 | If the implementation is hard to explain, it's a bad idea.
21 | If the implementation is easy to explain, it may be a good idea.
22 | Namespaces are one honking great idea -- let's do more of those!
--------------------------------------------------------------------------------
/ThePythonApprentice_Code/Chapter02/str-help.txt:
--------------------------------------------------------------------------------
1 | >>> help(str)
2 | Python Library Documentation: class str in module builtins
3 |
4 | class str(object)
5 | | str(object='') -> str
6 | | str(bytes_or_buffer[, encoding[, errors]]) -> str
7 | |
8 | | Create a new string object from the given object. If encoding or
9 | | errors is specified, then the object must expose a data buffer
10 | | that will be decoded using the given encoding and error handler.
11 | | Otherwise, returns the result of object.__str__() (if defined)
12 | | or repr(object).
13 | | encoding defaults to sys.getdefaultencoding().
14 | | errors defaults to 'strict'.
15 | |
16 | | Methods defined here:
17 | |
18 | | __add__(self, value, /)
19 | | Return self+value.
20 | |
21 | | __contains__(self, key, /)
22 | | Return key in self.
23 | |
24 | | __eq__(self, value, /)
25 | | Return self==value.
26 | |
27 | | __format__(...)
28 | | S.__format__(format_spec) -> str
29 | |
30 | | Return a formatted version of S as described by format_spec.
31 | |
32 | | __ge__(self, value, /)
33 | | Return self>=value.
34 | |
35 | | __getattribute__(self, name, /)
36 | | Return getattr(self, name).
37 | |
38 | | __getitem__(self, key, /)
39 | | Return self[key].
40 | |
41 | | __getnewargs__(...)
42 | |
43 | | __gt__(self, value, /)
44 | | Return self>value.
45 | |
46 | | __hash__(self, /)
47 | | Return hash(self).
48 | |
49 | | __iter__(self, /)
50 | | Implement iter(self).
51 | |
52 | | __le__(self, value, /)
53 | | Return self<=value.
54 | |
55 | | __len__(self, /)
56 | | Return len(self).
57 | |
58 | | __lt__(self, value, /)
59 | | Return self size of S in memory, in bytes
84 | |
85 | | __str__(self, /)
86 | | Return str(self).
87 | |
88 | | capitalize(...)
89 | | S.capitalize() -> str
90 | |
91 | | Return a capitalized version of S, i.e. make the first character
92 | | have upper case and the rest lower case.
93 | |
94 | | casefold(...)
95 | | S.casefold() -> str
96 | |
97 | | Return a version of S suitable for caseless comparisons.
98 | |
99 | | center(...)
100 | | S.center(width[, fillchar]) -> str
101 | |
102 | | Return S centered in a string of length width. Padding is
103 | | done using the specified fill character (default is a space)
104 | |
105 | | count(...)
106 | | S.count(sub[, start[, end]]) -> int
107 | |
108 | | Return the number of non-overlapping occurrences of substring sub in
109 | | string S[start:end]. Optional arguments start and end are
110 | | interpreted as in slice notation.
111 | |
112 | | encode(...)
113 | | S.encode(encoding='utf-8', errors='strict') -> bytes
114 | |
115 | | Encode S using the codec registered for encoding. Default encoding
116 | | is 'utf-8'. errors may be given to set a different error
117 | | handling scheme. Default is 'strict' meaning that encoding errors raise
118 | | a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
119 | | 'xmlcharrefreplace' as well as any other name registered with
120 | | codecs.register_error that can handle UnicodeEncodeErrors.
121 | |
122 | | endswith(...)
123 | | S.endswith(suffix[, start[, end]]) -> bool
124 | |
125 | | Return True if S ends with the specified suffix, False otherwise.
126 | | With optional start, test S beginning at that position.
127 | | With optional end, stop comparing S at that position.
128 | | suffix can also be a tuple of strings to try.
129 | |
130 | | expandtabs(...)
131 | | S.expandtabs(tabsize=8) -> str
132 | |
133 | | Return a copy of S where all tab characters are expanded using spaces.
134 | | If tabsize is not given, a tab size of 8 characters is assumed.
135 | |
136 | | find(...)
137 | | S.find(sub[, start[, end]]) -> int
138 | |
139 | | Return the lowest index in S where substring sub is found,
140 | | such that sub is contained within S[start:end]. Optional
141 | | arguments start and end are interpreted as in slice notation.
142 | |
143 | | Return -1 on failure.
144 | |
145 | | format(...)
146 | | S.format(*args, **kwargs) -> str
147 | |
148 | | Return a formatted version of S, using substitutions from args and kwargs.
149 | | The substitutions are identified by braces ('{' and '}').
150 | |
151 | | format_map(...)
152 | | S.format_map(mapping) -> str
153 | |
154 | | Return a formatted version of S, using substitutions from mapping.
155 | | The substitutions are identified by braces ('{' and '}').
156 | |
157 | | index(...)
158 | | S.index(sub[, start[, end]]) -> int
159 | |
160 | | Like S.find() but raise ValueError when the substring is not found.
161 | |
162 | | isalnum(...)
163 | | S.isalnum() -> bool
164 | |
165 | | Return True if all characters in S are alphanumeric
166 | | and there is at least one character in S, False otherwise.
167 | |
168 | | isalpha(...)
169 | | S.isalpha() -> bool
170 | |
171 | | Return True if all characters in S are alphabetic
172 | | and there is at least one character in S, False otherwise.
173 | |
174 | | isdecimal(...)
175 | | S.isdecimal() -> bool
176 | |
177 | | Return True if there are only decimal characters in S,
178 | | False otherwise.
179 | |
180 | | isdigit(...)
181 | | S.isdigit() -> bool
182 | |
183 | | Return True if all characters in S are digits
184 | | and there is at least one character in S, False otherwise.
185 | |
186 | | isidentifier(...)
187 | | S.isidentifier() -> bool
188 | |
189 | | Return True if S is a valid identifier according
190 | | to the language definition.
191 | |
192 | | Use keyword.iskeyword() to test for reserved identifiers
193 | | such as "def" and "class".
194 | |
195 | | islower(...)
196 | | S.islower() -> bool
197 | |
198 | | Return True if all cased characters in S are lowercase and there is
199 | | at least one cased character in S, False otherwise.
200 | |
201 | | isnumeric(...)
202 | | S.isnumeric() -> bool
203 | |
204 | | Return True if there are only numeric characters in S,
205 | | False otherwise.
206 | |
207 | | isprintable(...)
208 | | S.isprintable() -> bool
209 | |
210 | | Return True if all characters in S are considered
211 | | printable in repr() or S is empty, False otherwise.
212 | |
213 | | isspace(...)
214 | | S.isspace() -> bool
215 | |
216 | | Return True if all characters in S are whitespace
217 | | and there is at least one character in S, False otherwise.
218 | |
219 | | istitle(...)
220 | | S.istitle() -> bool
221 | |
222 | | Return True if S is a titlecased string and there is at least one
223 | | character in S, i.e. upper- and titlecase characters may only
224 | | follow uncased characters and lowercase characters only cased ones.
225 | | Return False otherwise.
226 | |
227 | | isupper(...)
228 | | S.isupper() -> bool
229 | |
230 | | Return True if all cased characters in S are uppercase and there is
231 | | at least one cased character in S, False otherwise.
232 | |
233 | | join(...)
234 | | S.join(iterable) -> str
235 | |
236 | | Return a string which is the concatenation of the strings in the
237 | | iterable. The separator between elements is S.
238 | |
239 | | ljust(...)
240 | | S.ljust(width[, fillchar]) -> str
241 | |
242 | | Return S left-justified in a Unicode string of length width. Padding is
243 | | done using the specified fill character (default is a space).
244 | |
245 | | lower(...)
246 | | S.lower() -> str
247 | |
248 | | Return a copy of the string S converted to lowercase.
249 | |
250 | | lstrip(...)
251 | | S.lstrip([chars]) -> str
252 | |
253 | | Return a copy of the string S with leading whitespace removed.
254 | | If chars is given and not None, remove characters in chars instead.
255 | |
256 | | partition(...)
257 | | S.partition(sep) -> (head, sep, tail)
258 | |
259 | | Search for the separator sep in S, and return the part before it,
260 | | the separator itself, and the part after it. If the separator is not
261 | | found, return S and two empty strings.
262 | |
263 | | replace(...)
264 | | S.replace(old, new[, count]) -> str
265 | |
266 | | Return a copy of S with all occurrences of substring
267 | | old replaced by new. If the optional argument count is
268 | | given, only the first count occurrences are replaced.
269 | |
270 | | rfind(...)
271 | | S.rfind(sub[, start[, end]]) -> int
272 | |
273 | | Return the highest index in S where substring sub is found,
274 | | such that sub is contained within S[start:end]. Optional
275 | | arguments start and end are interpreted as in slice notation.
276 | |
277 | | Return -1 on failure.
278 | |
279 | | rindex(...)
280 | | S.rindex(sub[, start[, end]]) -> int
281 | |
282 | | Like S.rfind() but raise ValueError when the substring is not found.
283 | |
284 | | rjust(...)
285 | | S.rjust(width[, fillchar]) -> str
286 | |
287 | | Return S right-justified in a string of length width. Padding is
288 | | done using the specified fill character (default is a space).
289 | |
290 | | rpartition(...)
291 | | S.rpartition(sep) -> (head, sep, tail)
292 | |
293 | | Search for the separator sep in S, starting at the end of S, and return
294 | | the part before it, the separator itself, and the part after it. If the
295 | | separator is not found, return two empty strings and S.
296 | |
297 | | rsplit(...)
298 | | S.rsplit(sep=None, maxsplit=-1) -> list of strings
299 | |
300 | | Return a list of the words in S, using sep as the
301 | | delimiter string, starting at the end of the string and
302 | | working to the front. If maxsplit is given, at most maxsplit
303 | | splits are done. If sep is not specified, any whitespace string
304 | | is a separator.
305 | |
306 | | rstrip(...)
307 | | S.rstrip([chars]) -> str
308 | |
309 | | Return a copy of the string S with trailing whitespace removed.
310 | | If chars is given and not None, remove characters in chars instead.
311 | |
312 | | split(...)
313 | | S.split(sep=None, maxsplit=-1) -> list of strings
314 | |
315 | | Return a list of the words in S, using sep as the
316 | | delimiter string. If maxsplit is given, at most maxsplit
317 | | splits are done. If sep is not specified or is None, any
318 | | whitespace string is a separator and empty strings are
319 | | removed from the result.
320 | |
321 | | splitlines(...)
322 | | S.splitlines([keepends]) -> list of strings
323 | |
324 | | Return a list of the lines in S, breaking at line boundaries.
325 | | Line breaks are not included in the resulting list unless keepends
326 | | is given and true.
327 | |
328 | | startswith(...)
329 | | S.startswith(prefix[, start[, end]]) -> bool
330 | |
331 | | Return True if S starts with the specified prefix, False otherwise.
332 | | With optional start, test S beginning at that position.
333 | | With optional end, stop comparing S at that position.
334 | | prefix can also be a tuple of strings to try.
335 | |
336 | | strip(...)
337 | | S.strip([chars]) -> str
338 | |
339 | | Return a copy of the string S with leading and trailing
340 | | whitespace removed.
341 | | If chars is given and not None, remove characters in chars instead.
342 | |
343 | | swapcase(...)
344 | | S.swapcase() -> str
345 | |
346 | | Return a copy of S with uppercase characters converted to lowercase
347 | | and vice versa.
348 | |
349 | | title(...)
350 | | S.title() -> str
351 | |
352 | | Return a titlecased version of S, i.e. words start with title case
353 | | characters, all remaining cased characters have lower case.
354 | |
355 | | translate(...)
356 | | S.translate(table) -> str
357 | |
358 | | Return a copy of the string S in which each character has been mapped
359 | | through the given translation table. The table must implement
360 | | lookup/indexing via __getitem__, for instance a dictionary or list,
361 | | mapping Unicode ordinals to Unicode ordinals, strings, or None. If
362 | | this operation raises LookupError, the character is left untouched.
363 | | Characters mapped to None are deleted.
364 | |
365 | | upper(...)
366 | | S.upper() -> str
367 | |
368 | | Return a copy of S converted to uppercase.
369 | |
370 | | zfill(...)
371 | | S.zfill(width) -> str
372 | |
373 | | Pad a numeric string S with zeros on the left, to fill a field
374 | | of the specified width. The string S is never truncated.
375 | |
376 | | ----------------------------------------------------------------------
377 | | Static methods defined here:
378 | |
379 | | maketrans(x, y=None, z=None, /)
380 | | Return a translation table usable for str.translate().
381 | |
382 | | If there is only one argument, it must be a dictionary mapping Unicode
383 | | ordinals (integers) or characters to Unicode ordinals, strings or None.
384 | | Character keys will be then converted to ordinals.
385 | | If there are two arguments, they must be strings of equal length, and
386 | | in the resulting dictionary, each character in x will be mapped to the
387 | | character at the same position in y. If there is a third argument, it
388 | | must be a string, whose characters will be mapped to None in the result.
389 |
--------------------------------------------------------------------------------
/ThePythonApprentice_Code/Chapter03/docstrings.repl:
--------------------------------------------------------------------------------
1 | $ python3
2 | Python 3.5.0 (default, Nov 3 2015, 13:17:02)
3 | [GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
4 | Type "help", "copyright", "credits" or "license" for more information.
5 | >>> from words import *
6 | >>> help(fetch_words)
7 |
8 | Help on function fetch_words in module words:
9 |
10 | fetch_words(url)
11 | Fetch a list of words from a URL.
12 |
13 | Args:
14 | url: The URL of a UTF-8 text document.
15 |
16 | Returns:
17 | A list of strings containing the words from
18 | the document.
19 | (END)
--------------------------------------------------------------------------------
/ThePythonApprentice_Code/Chapter03/docstrings2.repl:
--------------------------------------------------------------------------------
1 | $ python3
2 | Python 3.5.0 (default, Nov 3 2015, 13:17:02)
3 | [GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
4 | Type "help", "copyright", "credits" or "license" for more information.
5 | >>> import words
6 | >>> help(words)
7 |
8 | Help on module words:
9 |
10 | NAME
11 | words - Retrieve and print words from a URL.
12 |
13 | DESCRIPTION
14 | Usage:
15 |
16 | python3 words.py
17 |
18 | FUNCTIONS
19 | fetch_words(url)
20 | Fetch a list of words from a URL.
21 |
22 | Args:
23 | url: The URL of a UTF-8 text document.
24 |
25 | Returns:
26 | A list of strings containing the words from
27 | the document.
28 |
29 | main(url)
30 | Print each word from a text document from at a URL.
31 |
32 | Args:
33 | url: The URL of a UTF-8 text document.
34 |
35 | print_items(items)
36 | Print items one per line.
37 |
38 | Args:
39 | items: An iterable series of printable items.
40 |
41 | FILE
42 | /Users/sixtynorth/the-python-apprentice/words.py
43 |
44 | (END)
45 |
--------------------------------------------------------------------------------
/ThePythonApprentice_Code/Chapter03/import_words.repl:
--------------------------------------------------------------------------------
1 | $ python
2 | Python 3.5.0 (default, Nov 3 2015, 13:17:02)
3 | [GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
4 | Type "help", "copyright", "credits" or "license" for more information.
5 | >>> import words
6 | It
7 | was
8 | the
9 | best
10 | of
11 | times
12 | . . .
--------------------------------------------------------------------------------
/ThePythonApprentice_Code/Chapter03/main_index_error.repl:
--------------------------------------------------------------------------------
1 | $ python3
2 | Python 3.5.0 (default, Nov 3 2015, 13:17:02)
3 | [GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
4 | Type "help", "copyright", "credits" or "license" for more information.
5 | >>> from words import *
6 | >>> main()
7 | Traceback (most recent call last):
8 | File "", line 1, in
9 | File "/Users/sixtynorth/projects/sixty-north/the-python-apprentice/manuscript/code/pyfund/words.py", line 21, in main
10 | url = sys.argv[1]
11 | IndexError: list index out of range
12 | >>>
--------------------------------------------------------------------------------
/ThePythonApprentice_Code/Chapter03/words.1.py:
--------------------------------------------------------------------------------
1 | from urllib.request import urlopen
2 |
3 | with urlopen('http://sixty-north.com/c/t.txt') as story:
4 | story_words = []
5 | for line in story:
6 | line_words = line.decode('utf-8').split()
7 | for word in line_words:
8 | story_words.append(word)
9 |
--------------------------------------------------------------------------------
/ThePythonApprentice_Code/Chapter03/words.2.py:
--------------------------------------------------------------------------------
1 | from urllib.request import urlopen
2 |
3 |
4 | def fetch_words():
5 | with urlopen('http://sixty-north.com/c/t.txt') as story:
6 | story_words = []
7 | for line in story:
8 | line_words = line.decode('utf-8').split()
9 | for word in line_words:
10 | story_words.append(word)
11 |
12 | for word in story_words:
13 | print(word)
14 |
--------------------------------------------------------------------------------
/ThePythonApprentice_Code/Chapter03/words.3.main.py:
--------------------------------------------------------------------------------
1 | def main():
2 | words = fetch_words()
3 | print_words(words)
4 |
5 |
6 | if __name__ == '__main__':
7 | main()
8 |
--------------------------------------------------------------------------------
/ThePythonApprentice_Code/Chapter03/words.3.py:
--------------------------------------------------------------------------------
1 | from urllib.request import urlopen
2 |
3 |
4 | # This fetches the words and returns them as a list.
5 | def fetch_words():
6 | with urlopen('http://sixty-north.com/c/t.txt') as story:
7 | story_words = []
8 | for line in story:
9 | line_words = line.decode('utf-8').split()
10 | for word in line_words:
11 | story_words.append(word)
12 | return story_words
13 |
14 |
15 | # This prints a list of words
16 | def print_words(story_words):
17 | for word in story_words:
18 | print(word)
19 |
20 |
21 | if __name__ == '__main__':
22 | words = fetch_words()
23 | print_words(words)
24 |
--------------------------------------------------------------------------------
/ThePythonApprentice_Code/Chapter03/words.4.py:
--------------------------------------------------------------------------------
1 | from urllib.request import urlopen
2 |
3 |
4 | def fetch_words(url):
5 | with urlopen(url) as story:
6 | story_words = []
7 | for line in story:
8 | line_words = line.decode('utf-8').split()
9 | for word in line_words:
10 | story_words.append(word)
11 | return story_words
12 |
13 |
14 | def print_items(items):
15 | for item in items:
16 | print(item)
17 |
18 |
19 | def main():
20 | words = fetch_words()
21 | print_items(words)
22 |
23 | if __name__ == '__main__':
24 | main()
25 |
--------------------------------------------------------------------------------
/ThePythonApprentice_Code/Chapter03/words.5.py:
--------------------------------------------------------------------------------
1 | import sys
2 | from urllib.request import urlopen
3 |
4 |
5 | def fetch_words(url):
6 | with urlopen(url) as story:
7 | story_words = []
8 | for line in story:
9 | line_words = line.decode('utf-8').split()
10 | for word in line_words:
11 | story_words.append(word)
12 | return story_words
13 |
14 |
15 | def print_items(items):
16 | for item in items:
17 | print(item)
18 |
19 |
20 | def main(url):
21 | words = fetch_words(url)
22 | print_items(words)
23 |
24 | if __name__ == '__main__':
25 | main(sys.argv[1])
26 |
--------------------------------------------------------------------------------
/ThePythonApprentice_Code/Chapter03/words.6.py:
--------------------------------------------------------------------------------
1 | import sys
2 | from urllib.request import urlopen
3 |
4 |
5 | def fetch_words(url):
6 | """Fetch a list of words from a URL."""
7 | with urlopen(url) as story:
8 | story_words = []
9 | for line in story:
10 | line_words = line.decode('utf-8').split()
11 | for word in line_words:
12 | story_words.append(word)
13 | return story_words
14 |
15 |
16 | def print_items(items):
17 | for item in items:
18 | print(item)
19 |
20 |
21 | def main(url):
22 | words = fetch_words(url)
23 | print_items(words)
24 |
25 | if __name__ == '__main__':
26 | main(sys.argv[1])
27 |
--------------------------------------------------------------------------------
/ThePythonApprentice_Code/Chapter03/words.7.py:
--------------------------------------------------------------------------------
1 | """Retrieve and print words from a URL.
2 |
3 | Usage:
4 |
5 | python3 words.py
6 | """
7 |
8 | import sys
9 | from urllib.request import urlopen
10 |
11 |
12 | def fetch_words(url):
13 | """Fetch a list of words from a URL.
14 |
15 | Args:
16 | url: The URL of a UTF-8 text document.
17 |
18 | Returns:
19 | A list of strings containing the words from
20 | the document.
21 | """
22 | with urlopen(url) as story:
23 | story_words = []
24 | for line in story:
25 | line_words = line.decode('utf-8').split()
26 | for word in line_words:
27 | story_words.append(word)
28 | return story_words
29 |
30 |
31 | def print_items(items):
32 | """Print items one per line.
33 |
34 | Args:
35 | items: An iterable series of printable items.
36 | """
37 | for item in items:
38 | print(item)
39 |
40 |
41 | def main(url):
42 | """Print each word from a text document from at a URL.
43 |
44 | Args:
45 | url: The URL of a UTF-8 text document.
46 | """
47 | words = fetch_words(url)
48 | print_items(words)
49 |
50 | if __name__ == '__main__':
51 | main(sys.argv[1])
52 |
--------------------------------------------------------------------------------
/ThePythonApprentice_Code/README.txt:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------