To add and remove random letters to/from each word in a given string

Question:

The following code generates random typos:

# https://stackoverflow.com/a/51080546
import string
import random

phrase = "Lorem ipsum dolor sit amet, lorem ipsum."
# probability for a word to change
p = 0.8

new_phrase = []
words = phrase.split(' ')
for word in words:
    outcome = random.random()
    if outcome <= p:
        ix = random.choice(range(len(word)))
        new_word = ''.join([word[w] if w != ix else random.choice(string.ascii_letters) for w in range(len(word))])
        new_phrase.append(new_word)
    else:
        new_phrase.append(word)

new_phrase = ' '.join([w for w in new_phrase])

print(new_phrase)

How is it possible to make it also add and remove random letters to/from each word?

Asked By: jsx97

||

Answers:

To add random letters, change random.choice(string.ascii_letters) to word[w] + random.choice(string.ascii_letters).

To remove random letters, change random.choice(string.ascii_letters) to ''.

Answered By: mkrieger1
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.