If you are on Python 3.5 or better, do yourself a favor and learn to use pathlib.Path
objects. To find a file in your user home directory, simply do this:
from pathlib import Path
home_path = Path.home()
in_path = home_path/'word.txt'
Now in_path
is a path-like object pointing to a file called "word.txt" in the top of your user home directory. You can safely and easily get the text out of that object, and split it into individual words as well, this way:
text = in_path.read_text() # read_text opens and closes the file
text_words = text.split() # splits the contents into list of words at all whitespace
Use the append()
method to add words to your word list:
six_letter_words = []
for word in text_words:
if len(word) == 6:
six_letter_words.append(word)
The last 3 lines can be shortened using a list comprehension, which is very nice Python syntax for creating the list in place (without writing a for loop or using the append method):
six_letter_words = [word for word in words if len(word) == 6]
If you want to make sure you don't get words with numbers and punctuation, use an isalpha()
check:
six_letter_words = [word for word in words if len(word) == 6 and word.isalpha()]
If numbers are OK but you don't want punctuation, use an isalnum()
check:
six_letter_words = [word for word in words if len(word) == 6 and word.isalnum()]
Finally: for a random word in your list, use the choice
function from the random
module:
import random
random_word = random.choice(six_letter_words)