Question

I am new to Python..(I am studying it for a week or so) I am trying to import a file as a list and then I want to choose a random word from it to use it in a loop.? I am not very sure how to do it! Thanks in advance

No correct solution

OTHER TIPS

Here's the answer in a generalized form:

f = open("path/to/file", "r") # opens the file as read-only
content = f.read() # there are easier ways to do this, but....
### do whatever you're doing here....
f.close() # MAKE SURE YOU CLOSE FILES when you're done with them
# if you don't, you're asking for memory leaks.

You can also use a context manager, but it's slightly harder to read:

with open("path/to/file","r") as f:
    content = f.read() # again, this is not the BEST way....
    ### do stuff with your file
# it closes automatically, no need to call f.close()

Outside of file operations, here's string -> list stuff:

"a,b,c,d,e,f,g".split(',')
-> ['a','b','c','d','e','f','g']
# str.split creates a list from a string, splitting elements on
# whatever character you pass it.

And here's random.choice:

import random

random.choice(['a','b','c','d','e','f','g'])
-> 'c' # chosen by fair dice roll, guaranteed to be random! ;)
# random.choice returns a random element from the list you pass it

I'm going to give you an example that includes a few best practices:

my_list = [] 

Open the file with the context manager, with (which will automatically close the file if you have an error, as opposed to the other way you've been shown here), and with the Universal readlines, rU, flag enabled (r is the default).

with open('/path/file', 'rU') as file:
    for line in file:
        my_list.extend(line.split()) # this can represent processing the file line by line

The str.split() method will split on whitespace, leaving you with your punctuation. Use the Natural Language Toolkit if you really need words, which would help you preserve meaning better.

You could read the entire file all at once with

my_list = file.read().split()

And that may work for smaller files, but keep in mind difficulties with bigger files if you do this.

Use the random module to select your word (keep your imports to the top of your script, in most cases, though):

import random

my_random_word = random.choice(my_list)

i have completed the same assignment that you are doing! The way i did it was like this.

from hangman_words import word_list
from hangman_art import stages
from hangman_art import logo
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top