You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 74c8535
Browse filesBrowse the repository at this point in the historyBrowse files
@@ -212,7 +212,7 @@ This produces an (ordered) list of words::
212
212
213
213
Now you've got some words to play with. Once you think you've got it working, try a bit longer piece of text. But this will do for now, and it's small and simple enough that you can immediately see if your code is working.
214
214
215
-
You will find that example in the test file, so we can write tests agains it:
215
+
You will find that example in the test file, so we can write tests against it:
216
216
217
217
.. code-block:: python
218
218
@@ -222,25 +222,27 @@ You will find that example in the test file, so we can write tests agains it:
222
222
The trigrams structure
223
223
----------------------
224
224
225
-
From above, this is what you need to build up something like this::
225
+
Now we need to think a bit about what we want the trigrams structure to be.
226
226
227
-
"I wish" => ["I", "I"]
228
-
"wish I" => ["may", "might"]
229
-
"may I" => ["wish"]
230
-
"I may" => ["I"]
227
+
From above, we know that we need to build up something like this::
228
+
229
+
"I wish" =>"I", "I"
230
+
"wish I" =>"may", "might"
231
+
"may I" =>"wish"
232
+
"I may" =>"I"
231
233
232
234
Hmmm, in a way, that's almost pseudo code. You have a bunch of word pairs, and for each word pair, there are one or more words that follow it.
233
235
234
-
Those following words look a lot like they are in a list, yes? Perfect, the list structure keeps order, and you can keep adding (appending) new words to it.
236
+
Those following words look a lot like they could be in a list, yes? Perfect, the list structure keeps order, and you can keep adding (appending) new words to it.
235
237
236
-
Each of those lists of words needs to be mapped to a particular pair. Each pair is unique; it only shows up once (when that same pair is encountered again in the text, you add the follower to the list).
238
+
Each of those lists of words needs to be mapped to a particular pair. Each pair is unique; it only shows up once (when that same pair is encountered again in the text, you add the follower to the list of following words).
237
239
238
240
That sounds a lot like a dictionary. The keys (word pairs) are unique, and map to a list of following words. (Note that, technically, in python the dictionary is only one implementation of a
Now you have a choice of data structures: string or tuple.
243
+
Now you have a choice of data structures for the word pairs, or keys in the dict: a string or a tuple.
242
244
243
-
String: The keys are a pair of words and can be represented as a string of two words with a space like so:
245
+
**String**: The keys are a pair of words and can be represented as a string of two words with a space like so:
244
246
245
247
.. code-block:: python
246
248
@@ -250,7 +252,7 @@ String: The keys are a pair of words and can be represented as a string of two w
250
252
"I may": ["I"],
251
253
}
252
254
253
-
Tuple: But strings are not the only type that you can use as keys in a dict; you can use any *immutable* type. Recall that tuples are immutable (they can't be changed once they have been created). Since each pair of words is, well, a pair, it makes sense to store each pair in a tuple, keeping the individual words separate:
255
+
**Tuple**: But strings are not the only type that you can use as keys in a dictionary; you can use any *immutable* type. Recall that tuples are immutable (they can't be changed once they have been created). Since each pair of words is, well, a pair, it makes sense to store each pair in a tuple, keeping the individual words separate:
254
256
255
257
.. code-block:: python
256
258
@@ -260,46 +262,44 @@ Tuple: But strings are not the only type that you can use as keys in a dict; you
260
262
("I", "may"): ["I"],
261
263
}
262
264
263
-
I like the example that uses tuples better, but either one will work.
265
+
I like the version that uses tuples better, but either one will work. The test code is designed to check forword pairsin tuples. If you want to write your code using space separated strings, you can modify the tests.
264
266
265
267
Building the Trigrams dict
266
268
..........................
267
269
268
270
So you've got a list of words, and you need to build up a dict like one of the above.
269
271
270
-
It's time to create a python file and start writting some code!
272
+
It's time to create a python file and start writing some code!
273
+
274
+
Put this in your ``trigrams.py`` file
271
275
272
276
.. code-block:: python
273
277
274
278
#!/usr/bin/env python3
275
279
276
-
words = "I wish I may I wish I might".split()
277
-
278
-
279
-
def build_trigrams(words):
280
+
def build_trigram(words):
280
281
"""
281
282
build up the trigrams dict from the list of words
282
283
283
-
returns a dict with:
284
-
keys: word pairs
285
-
values: list of followers
284
+
:param words: a list of individual words in order
285
+
286
+
:returns: a dict with:
287
+
keys: word pairs in tuples
288
+
values: list of the words that follow the pain in the key
286
289
"""
290
+
287
291
trigrams = {}
288
292
289
293
# build up the dict here!
290
294
291
295
return trigrams
292
296
293
297
294
-
if __name__ == "__main__":
295
-
trigrams = build_trigrams(words)
296
-
print(trigrams)
297
-
298
298
So how do you actually build up that dict? That's kind of the point of the exercise, so I won't tell you that ... but here are some hints:
299
299
300
300
**Looping through the words**
301
301
302
-
Obviously you need to loop through all the words, so a ``for`` loop makes sense. However, this is a bit tricky. Usually in Python you loop through all the items in a list, and don't worry about the indices:
302
+
Obviously you need to loop through all the words, so a ``for`` loop makes sense. However, this is a bit tricky. Usually in Python you loop through all the items in a list, and don't worry about the indexes:
303
303
304
304
.. code-block:: python
305
305
@@ -331,18 +331,69 @@ For each pair in the text, you need to add it to the dict. But:
331
331
332
332
("wish", "I"): ["may", "might"]
333
333
334
-
Note that the example above suggests the basic logic; it's almost pseudo-code. And that logic will work. But it turns out that this is a common enough operation that python dicts have a method that lets you do that logic in one step? Can you find it?
334
+
Note that the description above suggests the basic logic; it's almost pseudo-code. And that logic will work. But it turns out that this is a common enough operation that python dicts have a method that lets you do that logic in one step? Can you find it?
You should now have code that will return a dict like we noted above::
338
+
As you develop this code, run the tests each time you think you have made some progress::
339
+
340
+
$ pytest test_trigrams.py
341
+
342
+
In that test file, there are two tests of the `trigrams()` function: One that tests that it gets the right word pairs as keys:
343
+
344
+
.. code-block:: python
345
+
346
+
def test_trigrams_pairs():
347
+
"""
348
+
test that the build_trigram function creates the right pairs of words
349
+
"""
350
+
tris = trigrams.build_trigram(IWISH)
351
+
352
+
pairs = tris.keys()
353
+
354
+
# using a set here, as the dict_keys object is a set as well
355
+
# And keys are always unique and hashable
356
+
# and the order does not matter, so perfect for a set
357
+
assert pairs == {("I", "wish"),
358
+
("wish", "I"),
359
+
("may", "I"),
360
+
("I", "may"),
361
+
}
362
+
363
+
and one that tests if the following word lists are correct:
364
+
365
+
.. code-block:: python
366
+
367
+
def test_trigrams_following_words():
368
+
"""
369
+
test that the following words are correct
370
+
"""
371
+
tris = trigrams.build_trigram(IWISH)
372
+
373
+
# this will only print if the test fails
374
+
# but if if does, you can see what's going on to try to fix it.
375
+
print(tris)
376
+
377
+
# a separate assert for each pair:
378
+
assert tris[("I", "wish")] == ["I", "I"]
379
+
assert tris[("wish", "I")] == ["may", "might"]
380
+
assert tris[("may", "I")] == ["wish"]
381
+
assert tris[("I", "may")] == ["I"]
382
+
383
+
Note that if the first test fails, almost certainly the second will too (the second test explicitly looks for all the same keys). That's OK. It's still good to keep them separate, because the first test could pass while the second one fails -- it's nice to know you've made progress!
384
+
385
+
If it seems like we have hard-coded a lot of detail in -- you are right. But this is quite deliberate. And it is why we chose such a simple set of words to start out with. If you want read a bit more about this approach, this blogger puts it nicely:
If both tests pass, you should now have code that will return a dict like we noted above::
339
389
340
390
{("I", "wish"): ["I", "I"],
341
391
("wish", "I"): ["may", "might"],
342
392
("may", "I"): ["wish"],
343
393
("I", "may"): ["I"]}
344
394
345
-
Try it out on a longer bit of text (your choice) before you go any further.
395
+
Try it out on a longer bit of text (your choice) before you go any further. If it doesn't work correctly, make sure to write a test that catches the problem before you fix it!
396
+
346
397
347
398
Using the Trigrams dict
348
399
.......................
@@ -361,18 +412,49 @@ This is the fun part. Once you have a mapping of word pairs to following words,
361
412
# pick a random item from a sequence
362
413
random.choice(a_list)
363
414
364
-
- You need to start with the first word pair; picking a random key from a dict is actually a bit tricky. Start with this known pair, and once you have the code working, you can figure out a better way to pick a pair to start with.
415
+
This is all pretty tricky to test -- after all, you are selecting random words -- you can't know what the result should be! There are two tactics you can take here. We show a bit of both in the provided tests.
416
+
417
+
Tactic one is to break you code down into pieces that you *can*test -- everything BUT the random choices.
418
+
419
+
Tactic two is to take advantage of the random "`seed <https://en.wikipedia.org/wiki/Random_seed>`_". Computers don't really make truly random numbers. What they do is compute a sequence of numbers that are statistically very much like random numbers. But if you start with the same initial value, known as the "seed", then you will get the same sequence of numbers. We can take advantage of this in our tests, as the built in ``random`` module provides a way to `set the seed <https://docs.python.org/3/library/random.html#random.seed>`_
420
+
421
+
The provided tests use a both of these tactics.
422
+
423
+
- You need to start with the first word pair; picking a random key from a dict is actually a bit tricky. But we have a test for it:
424
+
425
+
.. code-block:: python
426
+
427
+
def test_pick_random_pair():
428
+
test_pairs = {("one", "two"): [],
429
+
("one", "three"): [],
430
+
("four", "five"): [],
431
+
("six", "seven"): [],
432
+
("eight", "nine"): [],
433
+
}
434
+
# set the seed so we'll always get the same one
435
+
random.seed(1234)
436
+
pair = trigrams.pick_random_pair(test_pairs)
437
+
438
+
assert pair == ('six', 'seven')
439
+
440
+
So you'll need to define a function: ``pick_random_pair()`` that takes your trigram dict as input, and returns a random key.
441
+
442
+
Note that that particular result is using a particular algorithm -- if you use a different one, you might get a different pair -- but you should get the same one every time, so you can make the test check for that.
443
+
365
444
366
445
- As you build up your text, you probably want to build it up in a list, appending one word at a time. You can join it together at the end with ``" ".join(the_list_of_words)``
367
446
368
447
- Remember that after adding a word to a pair to make a three-word text, the next pair is the last two words in that three-word text.
369
448
370
-
- What to doif you end up with a word pair that isn't in the original text?
449
+
- What to do if you end up with a word pair that isn't in the original text? It's unlikely on a long text, but possible.
371
450
372
451
- How to terminate? Probably have a pre-defined length of text!
373
452
453
+
454
+
374
455
Once you have the basics working, try your code on a longer piece of input text. Then think about making it fancy. Can you make sentences with capitalized first words and punctuation? Anything else to make the text more "real"?
0 commit comments