16 The Scrambler: Randomly reordering the middles of words

 

Yuor brian is an azinamg cmiobiaontn of hdarware and sftraowe. Yoru’e rdineag tihs rhgit now eevn thgouh the wrdos are a mses, but yuor biran can mkae snese of it bceause the frsit and lsat ltrtees of ecah wrod hvae saeytd the smae. Yuor biran de’onst atlaulcy raed ecah lteetr of ecah wrod but rades wlohe wdors. The scamrbeld wrdos difteienly solw you dwon, but y’roue not rlleay eevn tyinrg to ulsrmbance the lrttees, are you? It jsut hnaepps!

In this exercise, we will write a program called scrambler.py that will scramble each word of the text given as an argument. The scrambling should only work on words with 4 characters or more and should only scramble the letters in the middle of the word, leaving the first and last characters unchanged. The program should take a -s or --seed option (an int with default None) to pass to random.seed().

It should handle text on the command line:

$ ./scrambler.py --seed 1 "foobar bazquux"
faobor buuzaqx

Or from a file:

$ cat ../inputs/spiders.txt
Don't worry, spiders,
I keep house
casually.
$ ./scrambler.py ../inputs/spiders.txt
D'not wrory, sdireps,
I keep hsuoe
csalluay.

Here’s a string diagram to help you think about it:

scrambler string

In this exercise, you will:

  • Use a regular expression to split text into words.
  • Use the random.shuffle() function to shuffle a list.
  • Create scrambled versions of words by shuffling the middle letters while leaving the first and last unchanged.

16.1  Writing scrambler.py

16.1.1  Breaking the text into lines and words

16.1.2  Capturing, non-capturing, and optional groups

16.1.3  Compiling a regex

16.1.4  Scrambling a word

16.1.5  Scrambling all the words

16.2  Solution

16.3  Discussion

16.3.1  Processing the text

16.3.2  Scrambling a word

16.4  Review

16.5  Going Further

sitemap