I have a txt file of hundreds of thousands of words. I need to get into some format (I think dictionary is the right thing?) where I can put into my script something along the lines of;
for i in word_list:
word_length = len(i)
print("Length of " i word_length, file=open("LengthOutput.txt", "a"))
Currently, the txt file of words is separated by each word being on a new line, if that helps. I've tried importing it to my python script with
From x import y
.... and similar, but it seems like it needs to be in some format to actually get imported? I've been looking around stackoverflow for a wile now and nothing seems to really cover this specifically but apologies if this is super-beginner stuff that I'm just really not understanding.
CodePudding user response:
A list would be the correct way to store the words. A dictionary requires a key-value pair and you don't need it in this case.
with open('filename.txt', 'r') as file:
x = [word.strip('\n') for word in file.readlines()]
CodePudding user response:
IIUC, if each word is in its own line, there is no need for a dictionary. Simply reading the lines into a list will do fine.
Something like this should work?
with open(filename) as file:
lines = file.readlines()
CodePudding user response:
What you are trying to do is to read a file. An import
statement is used when you want to, loosely speaking, use python code from another file.
The docs have a good introduction on reading and writing files -
To read a file, you first open the file, load the contents to memory and finally close the file.
f = open('my_wordfile.txt', 'r')
for line in f:
print(len(line))
f.close()
A better way is to use the with
statement and you can find more about that in the docs as well.