Created
November 15, 2021 03:00
-
-
Save JosephTLyons/1e78755c4e5784feda8c74db311e1bad to your computer and use it in GitHub Desktop.
A program that shuffles the characters of each word in a text file, while preserving the position of punctuation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import random | |
| def shuffle_word(word): | |
| shufflable_characters = [character for character in word if character.isalnum()] | |
| random.shuffle(shufflable_characters) | |
| word = [shufflable_characters.pop(0) if character.isalnum() else character for character in word] | |
| word = "".join(word) | |
| # Sanity check to ensure we've used the exact same number of letters as we initially collected | |
| assert len(shufflable_characters) == 0 | |
| return word | |
| with open("your_file_name_here.txt", "r") as file: | |
| for line in file: | |
| shuffled_words = [shuffle_word(word) for word in line.split()] | |
| new_line = " ".join(shuffled_words) | |
| print(new_line) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment