I have created a Python program that removes words from a list if they are not a certain length. I have set up a for
loop that cycles through my list and checks if each word is a length of 3 or greater. My code is as follows:
import string
text_file = open("ten-thousand-english-words.txt", "r")
lines = text_file.readlines()
text_file.close()
open('SortedWords.txt', 'w').close()
for i in lines:
print(len(i))
if len(i) >= 4:
sortedFile = open("SortedWords.txt", "a") # append mode
sortedFile.write(i)
sortedFile.close()
I wanted to create a new file that only copies the word over if it is 3 characters or longer.
For some reason it reads all the words in the list as 1 character longer than they actually are (e.g. the word “Hello” would return a length of 6 even though the number of letters is 5).
I fixed this by making it so that the length it looks for is 4 instead of 3, and it worked properly. I couldn't find any information about this issue online, so I decided to post this in case anyone knows why this happens.