http://learnpythonth.../book/ex41.html
So I'm trying to understand the script oop_test.py that he wrote by breaking things down piece by piece. And now I've finally hit the wall
I don't understand why MyTest code's snippet.count("###") gives me different results everytime I run it?
snippet.count("###") = 1
class_names = ['behavior']
------------------------------------------------------------
snippet.count("###") = 0
class_names = []
------------------------------------------------------------
snippet.count("###") = 1
class_names = ['Agreement']
------------------------------------------------------------
snippet.count("###") = 2
class_names = ['Attraction', 'Back']
------------------------------------------------------------
snippet.count("###") = 2
class_names = ['Bottle', 'Cough']
------------------------------------------------------------
snippet.count("###") = 0
class_names = []
Can somebody help explain to me what is going on in the def convert(snippet, phrase): function?
The results from this function confuses me
MyTest.py
import random
from urllib import urlopen
from pprint import pprint
# http://docs.python.org/2/tutorial/datastructures.html
WORD_URL = "http://learncodethehardway.org/words.txt"
WORDS = []
PHRASES = {
"class ###(###):":
"Make a class named ### that is-a ###.",
"class ###(object):\n\tdef __init___(self, ***)":
"class ### has-a __init__ that takes self and *** parameters.",
"class ###(object):\n\tdef ***(self, @@@)":
"class ### has-a function named *** that takes self and @@@ parameters.",
"*** = ###()":
"Set *** to an instance of class ###.",
"***.***(@@@)":
"From *** get the *** function, and call it with parameters self, @@@.",
"***.*** = '***'":
"From *** get the *** attribute and set it to '***'."
}
#--------------------------------------------------------------------
# Dictionary-Key
snippets = PHRASES.keys()
random.shuffle(snippets)
print "\n\tPRINT: snippets (Dictionary-Key)\n"
print snippets
print "\n\tPRETTY-PRINT: snippets (Dictionary-Key)\n"
pprint(snippets)
print
print '-' * 60
#--------------------------------------------------------------------
# Dictionary-Value
print "\nPRINT: phrase (Dictionary-Value)\n"
for snippet in snippets:
phrase = PHRASES[snippet]
print "\t*", phrase
print
print '-' * 60
#--------------------------------------------------------------------
# Load up the words from the website
for word in urlopen(WORD_URL).readlines():
WORDS.append(word.strip())
print "\n\tPRINT: words\n"
#print WORDS
#pprint(WORDS)
print '-' * 60
print
#--------------------------------------------------------------------
# http://www.tutorialspoint.com/python/list_count.htm
# http://pymotw.com/2/random/index.html
def convert(snippet, phrase):
class_names = [w.capitalize() for w in
random.sample(WORDS, snippet.count("###"))]
print 'snippet.count("###") = ', snippet.count("###")
print "class_names = ", class_names
convert(snippet, phrase)
print

New Topic/Question
Reply



MultiQuote



|