Home > Enterprise >  To number the blanks in a string
To number the blanks in a string

Time:10-05

Trying to make a memory test of sentences.

With given a sentence, the code picks 3 random words and make them into blanks. It also prints out the 'answers'.

The quick brown fox jumps over the lazy dog.               # original sentence

Working on:

import string, re
from random import sample

original = 'The quick brown fox jumps over the lazy dog.'
o_list = original.split()
picked = sorted(sample(range(1,len(o_list)), 3))

new_sentence = []

for idx, word in enumerate(o_list):
    if idx in picked:
        word = " _____ "
    else:
        word = word
    new_sentence.append(word)

new_sentence = " ".join(new_sentence)
print (new_sentence)

answers = [str(idx 1)   '.'   o_list[w]   '  ' for idx, w in enumerate(picked)]
print (''.join(answers))

Ouputs:

The quick brown  _____  jumps over  _____  lazy  _____     # question sentence
1.fox  2.the  3.dog.  

I want to number the blanks, like:

The quick brown  1. _____  jumps over  2. _____  lazy  3. _____

Tried a regex way but it only replaces them into blanks:

new_sentence = re.sub(r' _____ ', ' ', new_sentence)

What's the best way to achieve it? Thank you!

CodePudding user response:

You could do something like this:

import string, re
from random import sample

original = 'The quick brown fox jumps over the lazy dog.'
o_list = original.split()
picked = sorted(sample(range(1,len(o_list)), 3))

new_sentence = []
word_count = 1

for idx, word in enumerate(o_list):
    if idx in picked:
        word = f"{word_count}. _____ "
        word_count  = 1
    else:
        word = word
    new_sentence.append(word)

new_sentence = " ".join(new_sentence)
print (new_sentence)

answers = [str(idx 1)   '.'   o_list[w]   '  ' for idx, w in enumerate(picked)]
print (''.join(answers))

You simply add a word counter and increment it each time you replace a word.

Output:

The 1. _____  brown fox jumps 2. _____  the lazy 3. _____ 
1.quick  2.over  3.dog.  

CodePudding user response:

Is this what you want?

for idx in range(len(picked)):
    new_sentence = re.sub(r"[a-zA-Z0-9 ] _____ ", " %d. _____ " % (idx   1), new_sentence, 1)

output is like

'The quick brown 1. _____  jumps over 2. _____  lazy 3. _____ '
  • Related