I'm having trouble with creating a function that would generate a random word from a list of four-Letter words from a file called fiveLetterWords.txt. I know how to generate the list and print it but I can't seem to get the random part right. I have attached the fiveLetterWords.txt file at the bottom of this post. The point of creating this program is to generate a random word when the user types import randomWord and then secretWord = randomWord.getRandomFiveLetterWord().

import random
def getRandomFiveLetterWord(e):
    file = open(e, "r")
    t = file.read()
    randomWord = random.randint(file[0], file[-1])
    file.close()
    return randomWord
print "The Five-Letter Word Generator generates:", getRandomFiveLetterWord("fiveLetterWords.txt")
Traceback (most recent call last):
  File "H:/me/fiveLetterWordGenerator.py", line 8, in <module>
    print getRandomFiveLetterWord("fiveLetterWords.txt")
  File "H:/me/fiveLetterWordGenerator.py", line 5, in getRandomFiveLetterWord
    randomWord = random.randint(file[0], file[-1])
TypeError: 'file' object is unsubscriptable

There are a number of problems here. First of all, that text file contains five letter words that are all appended together without any whitespace whatsoever.

Secondly, do not use file as one of your variable names. As you can see above, file is highlighted in purple meaning that it is a reserved word in Python.

Third, as the error is telling you, you cannot use subscript notation on a file object (file). You read the contents of the file into the variable t. At the very least you should be trying to use subscripts on t (even though that would still be wrong).

randint returns a random integer, not a word. What you want is random.choice, which you would pass a *LIST* of words to. Not a gigantic single word that you're expecting the program to magically understand to be a listing of five letter words.

So first either break up your text file into words or write a small function to read in the file contents and return a list of words.
Then implement the proper random function.

Problem #1: My professor wants us to use that file...
Problem #2: He also wants us to use that format of opening a file.. which is strange and I do agree to you but it's better for me to follow what he says.
Problem #3 Ok fixed it to t instead.
Problem #4 Fixed it to random.choice() now

import random
def getRandomFiveLetterWord(e):
    file = open(e, "r")
    t = file.read()
    for line in file:
        randomWord = random.choice(t[0], t[-1])
    file.close()
    return randomWord

print "The Five-Letter Word Generator generates:", \
      getRandomFiveLetterWord("fiveLetterWords.txt")

Now I get..

UnboundLocalError: local variable 'randomWord' referenced before assignment
import random
def getRandomFiveLetterWord(e):
    file = open(e, "r")

That format of opening a file is not wrong its the fact that you're using 'file' as your variable name. Just change the name to something like fh (file handler) or similar. That is completely arbitrary.

t = file.read()
    for line in file:
        randomWord = random.choice(t[0], t[-1])

Here you are reading the entire file into 't', yet in your for loop you're iterating over the file object, which makes no sense, and is also the cause of your problem. Since you are reading the entire contents of the file, the file pointer traverses all the way through the file until it hits the EOF (end of file marker), which is where it sits until told otherwise.
When you try to perform for line in file the pointer is already at EOF so the for loop never runs, which is why randomWord is never declared and why you are receiving your error.
Furthermore, you still missed my point about what you pass to random.choice(). It's supposed to be a list. Whereas you are passing it the first and last character of the file contents. Why don't you try feeding some of this code into your interpreter (and here you will learn the strength of Python, being able to interact with your code to find problems); for your sake just try the following lines:

fh = open('fiveLetterWords.txt', "r")  # Open the file for reading
t = fh.read()    # Read the entire file contents in one pop
fh.close()  # Don't forget to close your file handles
print t   # print out what you read from the file
print t[0], t[-1]   # Print what you've been passing to random.choice

Perhaps after you do that little exercise you'll understand what I'm trying to say a little bit better. Your problem is that your text file is one gigantic line of garbage. Python cannot intuitively know that it is a very long list of concatenated five letter words. You need to split the file contents up into a list and pass that list to random.choice.

When I said the prof wanted me to use the file, I meant the file that has all those words clumped together.. not about format of opening a file. I'm almost done this problem yay! It took me a while about making a list out of it. I have an error about the random.choice... It says I have 3 arguments... but I only have 2 though...??

import random
def getRandomFiveLetterWord(e):
    fileList = []
    fh = open(e, "r")
    t = fh.read()
    g = 0
    h = 6
    for j in range (0,len(t)):
        if g <= len(t) and h <= len(t):
            splices = t[g:h]
            fileList.append(splices[:-1])
            g = g + 6
            h = h + 6
    randomWord = random.choice((fileList[0]), (len(fileList)))
    fh.close()
    return randomWord  
   

print "The Five-Letter Word Generator generates:", \
      getRandomFiveLetterWord("fiveLetterWords.txt")

You are almost there. Line 14 should be:
randomWord = random.choice(fileList)

Actually your text file has all the words listed on a separate line, so you can simplify this to ...

import random

def getRandomFiveLetterWord(e):
    fh = open(e, "r")
    fileList = fh.readlines()
    fh.close()
    randomWord = random.choice(fileList)
    return randomWord.rstrip()

print "The Five-Letter Word Generator generates:", \
      getRandomFiveLetterWord("fiveLetterWords.txt")

If you want to pick more than one random word, than it would be more pythonic to read the file only once (a time consuming operation), and your code would look like this ...

import random

def getRandomFiveLetterWord(fileList):
    """
    return a random word from the list
    strip off trailing whitespace
    """
    randomWord = random.choice(fileList)
    return randomWord.rstrip()


fh = open("fiveLetterWords.txt", "r")
fileList = fh.readlines()
fh.close()

print "The Five-Letter Word Generator generates:", \
      getRandomFiveLetterWord(fileList)

Yaayy!! It workss :D

Wow vegaseat.. that's just too simple an answer that it hurts... (the readline one)

Thank you soo much jlm699 and vegaseat!! I appreciate the help a lot!!

I officially declare this thread solved!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.