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

exchanging random words from file with my word

Hello I am working on a project that exchanges random words with my predefined word.
But because I am a begginer at python I cant see what I am doing wrong.
I am getting this error message: 'My file destination' line 21, in <module> splitText[randomWord] = "TEST" IndexError: list assignment index out of range

line 21 is splitText[randomWord] = "TEST"

Code:

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

import random, math

stringText = ""
# Reading from file.txt
fileX = open('LoremIpsum.txt','r')

for line in fileX:
     
    stringText += line
    splitText = stringText.split()
    
fileX.close()


# Theoretical number of changed words
editedWords = math.floor(len(stringText) / 4)   



# Trying to change the word at randomized index of the text
for specWord in range(editedWords):
    randomWord = random.randrange(0,len(stringText)-1)
    splitText[randomWord] = "TEST"
    print(randomWord)

print(splitText)

>Solution :

It’s because you’re using len(stringText) to determine the range for the random numbers. stringText is a string, so its length will be the number of characters in it. That’s way more than the length of splitText (which is a list of the words from stringText), because you have more characters than words in the string. It should work if you use len(splitText)-1 to calculcate the range of the random numbers.

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