Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 ''.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading