[Tutor] Re: problem writing random_word function
Nithya Soundararajan
s.varun at gmail.com
Mon Jul 19 20:32:18 CEST 2004
Hi, a better way for loading the file could be to convert it to pickle
form and then use it.(May be helpful only if you wanna load it with
two lines. ;-) ).
import pickle
f=open(yourfile,"r")
word_list=pickle.dump(f)
(this will work only if you hv already converted the hangman_words.txt
to pickle format, it will be easier for you and your code will look
more geekier.
Pour your comments
-Varun
On Mon, 19 Jul 2004 20:11:16 +0200, Karl Pflästerer) <sigurd at 12move.de> wrote:
> On 19 Jul 2004, Matt Smith <- smith-matt at tiscali.co.uk wrote:
>
> > Thanks Lloyd,
> > I've rewritten the function as below and everything seems to work
> > correctly.
>
> > def random_word(word_length):
> > """Returns a random word of length word_length"""
> > import random
> > f = open("hangman_words.txt","r")
> > word_list = []
> > while 1:
> > word = f.readline()
> > word = word.strip()
> > if word == "":
> > break
> > elif len(word) == word_length:
> > word_list = word_list + [word]
> > f.close()
> > return word_list[random.randint(0,(len(word_list)-1))]
>
> That function works but you could improve it a bit.
> First: don't import modules in functions. That may lead to dead locks.
>
> Second: you could write the above shorter and more pythonlike without
> the wile loop.
>
> Third: You mustn't forget that there may be no mathing word in your
> file.
>
> Fourth: don't hardwire the name of the file.
>
> import random
> def random_word (length, data="hangman_words.txt"):
> f = file(data)
> wordlist = [word for word in f if len(word.strip()) == length]
> f.close()
> if len(wordlist) > 0:
> return wordlist[random.randrange(0, len(wordlist))].strip()
>
> Karl
> --
> Please do *not* send copies of replies to me.
> I read the list
>
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list