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
Attachments
satyr
baker
parka
cafs
stork
lefts
skids
huffy
udder
yarns
pocks
techs
yeast
inure
yokel
dotty
truck
pales
links
ducat
swish
irked
aired
kirks
fades
shyer
sorta
floor
overs
flint
runes
torte
hanky
equip
lynch
motel
billy
ahead
spike
hotel
super
opine
buyer
tweed
waled
visor
grits
okras
dunks
glums
vouch
await
relay
savvy
withs
cross
napes
pass
cycle
froze
bushy
rusts
sprig
frank
misdo
outr
slits
trots
quads
grubs
glove
dungs
prank
women
owlet
divvy
gimpy
gybes
bevel
jeers
menus
stale
rills
tough
pried
baggy
these
lucks
tykes
gassy
purse
cynic
sings
looms
tunas
poohs
misty
worms
edict
buddy
quest
melds
gluey
silky
lowly
swain
theme
seeds
cramp
whims
berry
stein
goose
hunts
genii
sedge
caged
alter
antis
pithy
sleet
cunts
scars
hocks
queen
chant
merry
yawls
peeve
bloom
sylph
mores
toner
evils
acted
arrow
aquas
exact
eaten
wilts
sonar
dates
hired
flown
quaff
coral
disks
input
blush
lures
caulk
slump
loads
tryst
sloth
downy
bards
dents
fasts
crawl
route
niter
study
shoes
genes
cocky
buxom
snuff
fifes
waxed
gourd
chair
weirs
merer
freer
swath
tying
skews
exams
floss
visit
leans
holds
numbs
zebus
birth
boobs
enter
mimed
slows
lowed
shark
photo
veeps
rider
quill
diver
essay
silly
legit
sized
jelly
putts
horse
spoke
avows
style
skies
bones
cutes
hoofs
miffs
bicep
flock
cents
palls
keeps
banjo
kills
viola
umber
dicks
neigh
feeds
coats
pixie
tared
slime
facet
grays
verge
lions
pawed
amend
viced
rabid
satin
vexes
hoped
uncle
comma
rives
maker
edits
swift
blare
nines
rests
butts
scrod
druid
spots
ulnae
reels
fogey
first
pairs
sexed
corns
sited
timed
gooey
glare
wrote
lucid
pubic
helps
forts
narcs
doubt
velds
inner
eyrie
speck
yacht
doest
shahs
pigmy
zones
dogie
parks
softy
abuzz
joins
thees
prone
mowed
vanes
towns
rules
ville
loafs
modal
sepal
laded
loved
bleep
novas
nippy
staid
third
deans
burns
trued
wafer
state
safes
spasm
crone
glint
beats
tenon
store
samba
outed
plaza
pokes
dries
delis
cruet
verse
vasts
binge
basic
lauds
vizor
plans
dorks
natty
drill
bused
those
bared
times
rower
snide
whisk
gaunt
chunk
rheas
slave
thymi
elbow
rover
tired
smith
coals
gonad
males
latex
coins
joyed
sways
zonal
puffy
valve
vodka
loins
panic
pence
fucks
plods
pewee
ochre
cluck
socks
flats
shoon
nervy
shrug
pelts
brass
hooky
match
shied
umiak
tiles
ferns
pyxes
wants
biddy
astir
pests
conks
derby
texts
hauls
vivid
hubby
manse
salsa
smuts
niece
scant
towel
spade
surer
finds
pikes
slyer
fairs
roots
mates
folio
grout
leant
wafts
punts
pokey
aloft
humid
kiths
chock
miler
flash
bugle
cries
dairy
ogles
trace
copse
topic
forty
thank
sinus
light
funks
hulls
pools
mated
mange
vapor
prior
putty
cores
smirk
twits
heady
chore
reams
wombs
dicky
boxed
earls
sloes
sucks
named
groin
cited
fence
saned
solve
preen
patsy
spent
eider
swank
abuts
lotus
erred
tulip
parse
story
frets
sacks
amply
idles
levee
hails
clues
bulgy
ravel
mined
gangs
amigo
bossy
faker
discs
scamp
mynas
peter
covet
loans
ogres
serve
tolls
crisp
twine
navel
crabs
began
dived
feted
endow
blank
swell
minks
mooch
gnash
force
soils
chile
drays
bayou
cumin
offal
scald
axles
snots
allot
likes
walks
poxes
duchy
nails
inert
colas
culls
dunes
muled
cheek
annex
lolls
glitz
cello
filch
tines
rerun
riped
pound
truce
shone
ankhs
milks
musts
rinks
block
heave
gravy
ratty
gnats
abide
filmy
vises
fryer
chord
ledge
arson
mucus
vault
frays
sorry
stats
wheel
worst
yearn
kings
snail
model
stymy
glory
flood
sower
styes
catch
curvy
knave
pulse
burgs
terry
mauve
loped
loxes
endue
lites
thine
clung
snowy
autos
plain
bitch
reeds
bangs
copes
poise
slier
upend
fully
saris
hikes
flack
bowls
campy
punks
musty
scads
aught
moult
adorn
torsi
hafts
warms
risky
fraud
basal
trump
chime
metal
beret
feign
meows
whizz
corps
dares
moody
upper
xenon
loons
bingo
piggy
stone
canal
cuing
limbo
pulps
infix
craft
mails
bleed
honed
pinks
woofs
rifer
coded
woody
sabre
spite
alias
bleak
worse
incur
sawed
sober
loony
favor
gamin
peals
amped
fanny
japed
parch
embed
boars
rajas
riven
adopt
kneed
carve
focal
feint
helot
label
again
tries
liner
vista
swoon
boost
sooty
races
doing
bells
yolks
flaws
gulls
which
pinky
habit
ports
affix
knock
viand
seeps
curls
clunk
boast
raped
kiddy
beets
ripen
adman
yahoo
admit
rowed
brags
sails
crops
smell
thuds
direr
kopek
lives
bouts
ducks
coach
purge
honey
icily
lambs
pasha
sward
yuppy
squid
deism
books
docks
ramps
elite
worth
rides
metes
raged
depth
rifle
koala
mummy
payed
agent
quite
sense
halve
rares
tenet
merge
blame
porch
wiped
muddy
chick
chuck
hoops
perms
bible
wiser
sours
whist
booze
liens
cared
wordy
beset
juice
watts
fetid
waifs
malls
night
blitz
depot
hairy
lived
moors
bogey
guava
gushy
yokes
sneak
lasts
abode
junta
gated
bawdy
dines
vowed
gaits
chars
shush
slept
creel
wined
celli
wheat
ousts
tummy
specs
teach
dally
stack
comic
doped
buses
valid
trips
corny
askew
gelid
rainy
lanes
spire
nodal
damps
deeps
paper
unset
arose
strip
calls
slobs
obeys
leggy
brake
afoot
abeam
vixen
wormy
topaz
dandy
papal
farts
tarps
video
malts
swigs
fiery
lofty
grams
tango
abaft
panes
shack
fines
brunt
peony
fifth
apple
stave
emirs
towed
snits
delta
brigs
assay
fauns
wilds
jived
liege
sores
halts
poked
wanly
flaps
dodos
sagas
withe
roofs
razed
pines
treat
osier
shoos
spuds
mines
throb
poets
snout
curly
flied
bauds
wasps
titan
kinda
whens
pries
hurry
stole
polar
pates
swirl
octal
flits
argot
hypes
chill
evens
stars
kneel
verbs
nuder
spelt
musks
rugby
cords
dense
cubit
curse
ruses
beast
fleck
tents
umped
mucky
micra
lamed
faked
nudge
pails
mutes
phlox
sages
deter
anion
heaps
lemon
jeeps
while
lupus
isles
kiwis
jimmy
yours
aroma
mover
fuzes
above
charm
elide
sands
ain't
tings
opera
burnt
treks
funky
cloth
rails
ashes
awoke
sever
bolas
joust
scion
broom
keens
jolly
beans
forge
saith
pores
furry
wacko
humps
chide
heels
voice
legal
haven
mango
myths
skits
scoff
boles
brays
lined
gongs
tower
penal
drubs
hying
rinds
boney
basil
grunt
carol
knell
tends
tidal
group
rous
blips
flora
horns
bales
caked
twins
being
doled
necks
nixed
mites
takes
false
added
rebus
chain
inlay
tenth
field
water
emcee
fluky
maids
renal
nutty
tally
dears
sough
bribe
loges
taper
dudes
leach
cacti
spiky
rhyme
crest
banns
print
lithe
rogue
brine
chaps
hacks
hosed
cedar
whets
loose
bowed
duped
elect
filet
fussy
glued
snags
quote
scats
wisps
taboo
plant
dread
sorts
canoe
tunes
sound
rifts
balls
candy
slams
loves
omits
codas
tarot
steam
grabs
gurus
adis
torch
viral
fancy
scare
wanes
phase
troop
scram
hells
jumbo
allow
shale
swarm
trout
prune
dumpy
issue
dolly
anvil
bigot
fluke
alder
tract
shins
honks
cabal
clops
repay
caped
laxly
we'll
saves
fiber
nudes
south
torts
slate
ferry
minty
drape
boded
gnawn
sites
shade
coled
hymen
sassy
spilt
exile
brown
dicey
papaw
heros
bunch
abler
viper
bison
blurt
pupal
least
moons
today
mumps
amiss
learn
pearl
lusty
thrum
bozos
beeps
qualm
jetty
grate
addle
bongs
shelf
oddly
schwa
wades
odder
drive
mazes
heart
fusty
dowse
geode
growl
runny
lyres
stuff
frisk
steed
swept
cache
razor
guide
piper
typos
iotas
lemme
skulk
moats
caper
tense
reins
drops
flies
momma
gulag
items
trash
newsy
forgo
envoy
clipt
pipit
pilot
tamps
flags
bosom
sames
cleft
touch
laxer
attar
bongo
calyx
rocky
croup
peaks
brisk
humus
feuds
belie
still
foams
tipsy
disco
shrew
bogie
bolts
flaks
baste
avert
scone
fowls
monks
ivies
cites
cheap
rears
bonds
cacao
utter
moles
juicy
sumps
slags
fared
panty
diced
rayon
igloo
masts
staph
badly
tacky
coped
poops
brier
wrack
fling
flame
hello
pussy
gilds
forms
scout
goals
crepe
floes
users
deice
fouls
keels
sises
serfs
shred
ivory
shirr
dawns
medal
shall
halon
rival
pagan
mutts
toads
stink
jibed
staff
burps
calve
sling
pukes
recta
opium
quids
binds
frizz
hates
shoal
itchy
grads
clogs
gores
carry
haste
leery
prick
hotly
canes
felon
bakes
bases
brawl
reign
wicks
cysts
fleas
faded
hives
daunt
mamas
won't
title
golfs
germs
blahs
venom
crows
swine
burro
spout
steel
raspy
chomp
vised
yawed
flier
bleat
slurp
tsars
codes
newts
mires
pesky
mired
hazel
voids
freed
psych
divan
quire
turfs
snack
brick
decry
noble
plump
dosed
unwed
gazes
payee
there
ethos
nappy
organ
ruler
typed
drone
gnaws
relax
crate
loses
house
miser
debit
elegy
shave
snaky
cured
crave
bland
cameo
sulks
tepee
fiend
rebut
mopes
firms
mooed
hover
tepid
climb
jello
casts
knees
gawks
strop
sager
anode
livid
bayed
owing
tulle
works
grind
kayak
decor
hooch
sumac
troys
fitly
foamy
moire
grape
maced
glows
pumas
probe
clove
karat
boxes
goats
winch
wagon
lazes
mares
child
cowed
gluts
adore
butte
stead
spicy
olden
steal
acing
padre
waked
beach
marks
pease
doily
stump
pills
level
unify
whams
aerie
meets
beads
mount
maims
pouch
shaft
hazes
stake
credo
whiny
tribe
bight
alpha
bores
mynah
ripes
emery
labor
blued
fries
liter
bassi
ocher
loser
traps
rangy
brews
upset
think
stops
brain
stand
fluff
ended
smear
lamas
baths
feats
noels
seres
total
roads
muffs
norms
scary
bulky
cause
sheik
quail
chugs
whats
wales
pique
lymph
flake
brads
infer
gauzy
eases
jazzy
colts
salvo
hooks
place
mints
ocean
eject
refed
recap
wacky
break
mourn
pawls
files
clans
parry
moans
truth
kudos
trite
podia
three
horde
funds
wowed
crowd
threw
shims
braid
drool
music
shirt
raise
makes
stark
lemma
eagle
cavil
sixty
patch
ethic
twerp
wider
edify
twang
bulge
tones
jocks
poser
tardy
vogue
urban
bluer
pecan
front
spume
knead
hence
jerky
oozed
cigar
adobe
tutor
mommy
puree
y'all
lusts
stabs
psalm
guest
stomp
axing
salts
miens
churl
loamy
cairn
setup
hoots
valor
meter
aside
coops
baled
lubes
drily
ducts
kitty
annoy
green
aloud
exude
acrid
spies
space
lames
verve
clerk
ghost
bimbo
voter
togae
rocks
blabs
donor
minis
cheep
sinks
tauts
nerds
extol
dames
iring
siege
peril
loots
flows
inapt
mogul
halls
bunks
toque
toady
raids
rafts
sirup
coifs
pours
mixes
width
glide
fords
anise
queer
ounce
pured
glops
unity
shuts
crews
libel
wimpy
oxbow
aimed
brash
weeps
clang
nicer
luaus
piece
wager
puppy
where
avail
angle
hopes
armed
batty
tubes
gives
scowl
teeth
tonne
cawed
tizzy
tapes
warts
glade
build
genus
dills
weigh
shell
holed
bends
fists
lubed
spats
ingot
broad
barns
maria
youth
appal
tubae
wight
spied
pooch
matzo
lobes
honor
drams
turns
radio
studs
drums
drier
trill
knelt
prose
waved
tests
slued
haded
styli
howls
peers
royal
dusty
letup
gents
stirs
dikes
longs
fired
hours
swear
liked
vivas
tints
gasps
maple
lingo
rimed
serer
among
nabob
names
tiger
lunar
plea

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!!!

This question has already been answered. Start a new discussion instead.