Thursday 4 January 2024

LineRandomizer in Python : Utility Function

While Memorizing vocab for GRE, I decided to jumble up my word list in random order. This small python utility program helped me achieve that. Hope it helps you as well. 


'''
Author: Kunal Krishna
Date: 30/05/2023
'''

'''
Programme Purpose : Given a text file containing N lines,
    return a new file which has reorder those lines in random order.
    This has many utilities e.g. in memorizing a list of vocabulary.
Input: File1.text :
    >a
    >b
    >c
Output: File2.text : Random ordering
    >c
    >a
    >b
'''

import os
import re
import random
import numpy as np

# 1. Open file.txt : https://docs.python.org/3/library/functions.html#open
inpFile= open("D:\[win.kunal]\Desktop\Diff_Words.txt","r")
linesList = inpFile.readlines() #list of lines
# for line in linesList :
#     line = line.strip("\n")

# 2. Create an output file
resPath= "D:\my_codes\py_code\LineRandomizer"
resFileName = 'Difficult_Words.txt'
file_result = open(os.path.join(resPath,resFileName), "w") # w : creates/overrides existing
# alternatively
# file_result = open("Difficult_Words.txt", "w")

count = 0
# 3.Process the lines : randomize
while (len(linesList) > 0) :
    #chose a random word from the list
    random_word = np.random.choice(linesList)

    validWordExpression = "[~\*\#\w\s]"
    if( len(random_word.strip()) >0
            and re.match(validWordExpression, random_word) ) :
        # write the random word in the new file
        print(str(count+1)+". inserting..." + random_word.upper())
        file_result.write(random_word.upper())
        count +=1

    #also remove the word from linesList to avoid repetation
    linesList.remove(random_word)

# 4. Close the file
inpFile.close()
file_result.close()
if count>0 :  
    print(str(count)+" words inserted successfully!!!")
else :  
    print("No word(s) inserted.")

No comments:

Post a Comment