Arrays--part 3.
To create an array:
words = ["horse", "dog", "cow"]
creates a list with 3 elements--you can reference these elements singly
as words[0], words[1],
and words[2].
so, for example:
for i in range(3):
print words[i]
would print out the words in this list. If you want to add a 4th
word, "heffalump", you can do
words.append("heffalump")
and heffalump becomes words[3], so there are now 4 words in the
list.
-------------------------------------
A more flexible way of having a list in your program is to create on in
your Python IDLE GUI:
horse
dog
pig
heffalump
woozle
etc one word per line--call this, say, mywords.txt (it's
NOT a Python program, but a data set).
Then to read in the words:
words =
[]
this creates an initial empty list
numwds =
0
we'll keep track of how
many words there are
file = open('mywords.txt')
this opens the data file for reading
for line in
file:
a variation on a for loop
words.append(line)
adds the word to the list
numwds = numwds + 1
keeps track of how many words we have so far
We can then do
for j in range(numwds):
print
words[j]
to print out all the words
------------------------------------------
If you want to write the words to another file:
outfile =
open('copy.txt','w')
opens the file for writing
for j in range(numwds):
outfile.write(words[j])
outfile.close()
closes the file
---------------
what also works for input is
file = open('mywords.txt','r')
for line in file.readlines():
words.append(line)
numwds = numwds + 1
there are also other variations
----------------------------------------------------
Creating nonsense sentences, poetry, etc. (note the blank after each
word so they don't run together)
arts=["a ", "the ", "one "]
adjs=["green ", "fuzzy ", "purple ", "bloated "]
nouns = ["boy ","cow ", "bicycle ", "fish "]
verbs=["ran over ", "ate ", "saw ", "was chased by "]
then using randon.randrange, pick out an article, an adjective, a noun,
a verb, an article adjective, and noun.
you can have
sentence=arts[random.randrange(3)] + adjs[random.randrange(4)] +
nouns[random.randrange(4)]+\
verbs[random.randrange(4)] + arts[random.randrange(3)] +
adjs[random.randrange(4)] +\
nouns[random.randrange(4)]
and then print sentence works. note that the backslashes let you
continue this long statement on the next
line. For poetry, you might have several sets of nouns--and have
sentence1 pick its final noun from nouns2,
sentence2 picks its final noun from nouns3. nouns2 and nouns3
would be arrays of nouns that rhyme--e.g.
nouns2=["fool ", "school ", "mule "] and nouns3=["pule ", "yule ",
"ghoul "] etc.
also--for amusement, google "computer poetry", "computer haiku",
"computer sentences", and also, for
a contrast google "ginsburg + howl" to see human poetry that doesn't
sound all that different from what you
might generate.