112k views
2 votes
read a file called filled in with a few sentences or a paragraph. Then write a function called typoglycemia, which scrambles the letters in the words in the file leaving the first and last characters unchanged and then writes the results to a new file called "scrambled.txt".Save the file

1 Answer

6 votes

Answer:

def typoglycemia():

import random

punct = (".", ";", "!", "?", ",")

count = 0

new_word = ""

inputfile = input("Enter input file name:")

with open(inputfile, 'r') as fin:

for line in fin.readlines(): #Read line by line in txt file

for word in line.split(): # Read word by word in each line

if len(word) > 3: # If word length >3

'''If word ends with punctuation, Remove first letter, last letter and punctuation

shuffle the words: Add the removed letters at their respective positions'''

if word.endswith(punct):

word1 = word[1:-2]

word1 = random.sample(word1, len(word1))

word1.insert(0, word[0])

word1.append(word[-2])

word1.append(word[-1])

''' If there is no punctuation mark: Remove first and last letter.

Shuffle the word then add removed letters at their respective position'''

else:

word1 = word[1:-1]

word1 = random.sample(word1, len(word1))

word1.insert(0, word[0])

word1.append(word[-1])

new_word = new_word + ''.join(word1) + " "

''' If word length <3, just append the word and " " to the the previous words'''

else:

new_word = new_word + word + " "

with open((inputfile[:-4] + "scrambled.txt), 'a+') as fout:

fout.write(new_word + "\\")

new_word = ""

User Spoida
by
6.0k points