Open In App

Python | Scramble words from a text file

Last Updated : 11 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given some data in a text file, the task is to scramble the text and output in a separate text file. So, we need to write a Python program that reads a text file, scrambles the words in the file and writes the output to a new text file.

Rules to be followed: 

  • Words less than or equal to 3 characters need not be scrambled.
  • Don’t scramble first and last char, so Scrambling can become Srbmnacilg or Srbmnailcg or Snmbracilg, i.e. letters except first and last can be scrambled in any order.
  • Punctuation at the end of the word to be maintained as is i.e. “Surprising, ” could become “Spsirnirug, ” but not “Spsirn, irug”.
  • Following punctuation marks are to be supported – Comma Question mark, Full stop, Semicolon, Exclamation.
  • Do this for a file and maintain sequences of lines.

On executing the program, it should prompt the user to enter input file name and generate an output file with scrambled text. The output file should be named by appending the word “Scrambled” to the input file name.

Example: 

Input :  MyFile.txt ->
  
Scrambling words is very  
interesting. Because even  
if they are scrambled, it   
doesn't impact our   
reading. Because we don't 
read letter by letter, we 
read the word as a whole.   

Output : MyFileScrambled.txt ->
  
Srbmnacilg words is very   
itrensientg. Bscauee even  
if tehy are srelabcmd, it  
dosn'et ipcmat our 
raidneg. Bacusee we dn'ot 
raed lteetr by letetr, we 
raed the word as a wolhe.

Below is the implementation :  

Python3




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 firstletter, lastletter and punctuation
                      Shuffle the words
                      Add the removed letters (first letter)
                      Add the removed letters (last letter)
                      Add the removed letters (punctuation mark)'''
  
                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 letter and last letter
                      Shuffle the word
                      Add the removed letters (first letter)
                      Add the removed letters (last letter)
                      Append the word and " " to the previous words'''
  
                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 previous words'''
  
        else:
            new_word = new_word + word + " "
  
        # "Append to <filename>Scrambled.txt"
  
with open((inputfile[:-4] + "Scrambled.txt"), 'a+') as fout:
    fout.write(new_word + "\n")
  
new_word = ""


Output: 

Smcinrablg wodrs very Bauscee eevn tehy dnoes't
icpamt Bcuesae d'not read lteter raed wrod whole. 

 



Similar Reads

Python | Scramble strings in list
Sometimes, while working with different applications, we can come across a problem in which we require to shuffle all the strings in the list input we get. This kind of problem can particularly occur in gaming domain. Let's discuss certain ways in which this problem can be solved. Method #1 : Using list comprehension + sample() + join() The combina
5 min read
Python | Finding 'n' Character Words in a Text File
This article aims to find words with a certain number of characters. In the code mentioned below, a Python program is given to find the words containing three characters in the text file. Example Input: Hello, how are you ? , n=3 Output: how are you Explanation: Output contains every character of the of length 3 from the input file.Input File: File
3 min read
Python Program to Count Words in Text File
In this article, we are going to see how to count words in Text Files using Python. Example 1: Count String Words First, we create a text file of which we want to count the number of words. Let this file be SampleFile.txt with the following contents: File for demonstration:Below is the implementation: C/C++ Code # creating variable to store the # n
3 min read
Python Program to Find the Number of Unique Words in Text File
Given a text file, write a python program to find the number of unique words in the given text file in Python. Examples: Input: gfg.txt Output: 18 Contents of gfg.txt: GeeksforGeeks was created with a goal in mind to provide well written well thought and well explained solutions for selected questions Explanation: Frequency of words in the file are
2 min read
How to Use Words in a Text File as Variables in Python
We are given a txt file and our task is to find out the way by which we can use word in the txt file as a variable in Python. In this article, we will see how we can use word inside a text file as a variable in Python. Example: Input: fruits.txt apple banana orange Output: apple = Fruit banana = Fruit orange = Fruit Explanation: Here, we are using
3 min read
Convert Text and Text File to PDF using Python
PDFs are one of the most important and widely used digital media. PDF stands for Portable Document Format. It uses .pdf extension. It is used to present and exchange documents reliably, independent of software, hardware, or operating system. Converting a given text or a text file to PDF (Portable Document Format) is one of the basic requirements in
3 min read
Python - Compute the frequency of words after removing stop words and stemming
In this article we are going to tokenize sentence, paragraph, and webpage contents using the NLTK toolkit in the python environment then we will remove stop words and apply stemming on the contents of sentences, paragraphs, and webpage. Finally, we will Compute the frequency of words after removing stop words and stemming. Modules Needed bs4: Beaut
8 min read
Python - Get number of characters, words, spaces and lines in a file
Given a text file fname, the task is to count the total number of characters, words, spaces, and lines in the file. Python - Get number of characters, words, spaces and lines in a fileAs we know, Python provides multiple in-built features and modules for handling files. Let's discuss different ways to calculate the total number of characters, words
6 min read
Change the color of certain words in the tkinter text widget
Python has various options for Graphical User Interface (GUI) development. One of the options is Tkinter. Tkinter and Python together provide a faster way for GUI development. The Tk GUI toolkit provides an object-oriented interface. For creating GUI applications using Tkinter we have to follow a few steps – Import Tkinter module.Create the main wi
3 min read
Python: Convert Speech to text and text to Speech
Speech Recognition is an important feature in several applications used such as home automation, artificial intelligence, etc. This article aims to provide an introduction on how to make use of the SpeechRecognition and pyttsx3 library of Python.Installation required: Python Speech Recognition module: pip install speechrecognition PyAudio: Use the
3 min read
Article Tags :
Practice Tags :