Reputation: 9
I am trying to use a .txt file as a local database for around 4000 different words. They are organized in the following format:
wordOne
wordTwo
wordThree
wordFour
...
wordFourThousand
Each word has it's own separate line. My goal is to be able to import a specific word from this text file based on a random variable. I put an example of what I have so far below. Ignore my crummy camelCase habit.
import random
wordName=random.randint(1,4000)
with open('wordList.txt') as wordList:
#use the variable wordName to open the word on that particular line number in the .txt file and set it as a variable named wordString
print(wordString)
So if the variable wordName is equal to 32, it will open up the word on line 32 of the text file and print it to the console. I hope this isn't too easy of a question, I am a bit new to Python and trying to get some practice moving data from one source to another. I really appreciate the help!
Upvotes: 0
Views: 457
Reputation: 1
the easiest way to do what you have described is using the read lines methods.
Assuming the below is your text file
words.txt:
one
two
three
...
You would do the following:
with open("words.txt") as textFile:
words = textFile.readlines()
print(words[1])
output
two
Remember the list index start from zero, so if you wanted words[i]
where i = 1
to return the first element you would do words[i + 1]
.
Upvotes: 0
Reputation: 34282
Reading 4k words into memory is peanuts, so I'd not optimize anything here. The simplest approach is using random.choice()
:
import random
with open('filename.txt') as fp:
words = list(fp)
random_word = random.choice(words).strip() # strip will remove the trailing \n
Upvotes: 0
Reputation: 73
You can do:
words = wordlist.readlines()
then can do:
words[wordName - 1]
to retrieve the word you want, also you won't have to reopen the text file if you save words as a global variable.
Upvotes: 1