|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
AT&T devCentral & BlackBerry(r) Webcast Series: BlackBerry and GPS -Build Location Awareness into your BlackBerry Applications, July 10th-1:00PM EST. Register Today!
|
|
#1
|
|||
|
|||
|
Python programing newbie needs help
Hello
I am new to the forum and I was wondering if some of you may be able to help me with a program I need to create. It seems pretty simple, but I don't know how to go about it. So here is the problem. I have to create a mad lib. There are 4 diffrent text files containing the madlis. I am suppose to first prompt the user to enter one of the 4 files, if file name does not exists, error msg and prompt again. After it loads one file, it should ask him to input about 8-10 diffrent verbs and nouns and what not, which then should be put into loaded text at designated places. Once thety have been placed into designated places, tghe program should prompt the user to save the file, asking for name and yes/no if they want to save. I am stuck with this thing, I am by no means a programer, it was just a course I had to take for credits. If someone can help me out with a code or, code framents of where to start would be great thanks. -SuperDude |
|
#2
|
||||
|
||||
|
Have you got any code written so far? You seem to have the logic of the code worked out, so if you've gone through some Python tutorials it shouldn't be too difficult to do.
I'm reluctant to just hand people code for assignments on a plate. I'm happy to suggest changes and amendments to any code you post, however. |
|
#3
|
||||
|
||||
|
Sounds like fun, i'm assuming the user is asked where the verbs etc. are inserted?
Writing a Python program that knows the correct place to insert them into the file could be hard, you'd have to make it understand english too a degree and too be honest, who understand english ![]() Mark. |
|
#4
|
|||
|
|||
|
OK well i got some of it done
I = raw_input("enter a noun: ") N = raw_input("enter a verb: ") C = raw_input("enter noun: ") D = raw_input("enter noun: ") E = raw_input("enter a plural noun: ") F = raw_input("enter a verb: ") G = raw_input("enter another verb: ") H = raw_input("enter a adverb: ") J = raw_input("enter a noun: ") print "first line" , I, "." print "second line" , N, "." print "third line" , C, "." print "forth line" , D, "." print "fifth line" , E, "." print "sixth line" , F, "." print "seventh line" , G, "." print "eighth line" , H, "." print "nineth line" , J, "." But here is the thing, i dont know if i want to use the print commant so many times, because i have a paragaph right and i guess it would be messy. Also i heard there was like some sort of find command so that it can search in text, so maybe i can in text put like numbers and then the proggy can find the number and replace it with the inputed word. Also whats to prompt and save a file ... |
|
#5
|
|||
|
|||
|
Here is the updated code
Code:
print
selection = raw_input("Please enter a filename to read: ")
while selection != ("nytimes.py" or "bill.py" or "py.py"):
print("Error that file does not exist!")
selection = raw_input("Please enter a filename to read: ")
break
if selection == ("nytimes.py"):
ing_verb1 = raw_input("Please enter a ing verb: ")
verb1 = raw_input("Please enter a verb: ")
noun1 = raw_input("Please enter noun: ")
adjective1 = raw_input("Please enter adjective: ")
verb2 = raw_input("Please enter a verb: ")
er_adjective1 = raw_input("Please enter a er adjective: ")
adjective2 = raw_input("Please enter adjective: ")
verb3 = raw_input("Please enter a verb: ")
ing_verb2 = raw_input("Please enter a ing verb: ")
adjective3 = raw_input("Please enter a adjective: ")
verb4 = raw_input("Please enter a verb: ")
plural_noun1 = raw_input("Please enter a plural noun: ")
ed_verb1 = raw_input("Please enter a ed verb: ")
plural_noun2 = raw_input("Please enter a plural noun: ")
adjective4 = raw_input("Please enter a adjective: ")
proper_name1 = raw_input("Please enter a proper name: ")
profession1 = raw_input("Please enter a profession: ")
acronym1 = raw_input("Please enter a acronym: ")
ed_verb2 = raw_input("Please enter a ed verb: ")
noun2 = raw_input("Please enter a noun: ")
adjective5 = raw_input("Please enter a adjective: ")
city1 = raw_input("Please enter a city: ")
car_part1 = raw_input("Please enter a car part: ")
car_part2 = raw_input("Please enter a car part: ")
number1 = raw_input("Please enter a number: ")
proper_name2 = raw_input("Please enter a proper name: ")
adjective6 = raw_input("Please enter a adjective: ")
preposition1 = raw_input("Please enter a preposition: ")
adverb1 = raw_input("Please enter a adverb: ")
ing_verb3 = raw_input("Please enter a ing verb: ")
noun3 = raw_input("Please enter a noun: ")
adverb2 = raw_input("Please enter a adverb: ")
adjective7 = raw_input("Please enter a adjective: ")
ing_verb4 = raw_input("Please enter a ing verb: ")
verb5 = raw_input("Please enter a verb: ")
nytimes = "October 22, 2003 The New York Times--TECHNOLOGY
<ing_verb> Soon: Smarter Ways to <verb>, Turn and Cruise
By TIM MORAN
Your <noun> is becoming a much <adjective> driver.
It can already <verb> the brakes to avoid a skid far <er_adjective> than the
most skillful driver; turn on its <plural_noun> when darkness falls; activate
its <adjective> wipers when it starts to <verb>; and avoid <ing_verb> the wheels
on <adjective> pavement.
Just <verb> though. As new <plural_noun> that are still being tested by auto
suppliers are <ed_verb> mostly in luxury models, the <plural_noun> will work
to prevent driver mistakes.
Enhanced <adjective> Control
<proper_name> Cossins, the chief <profession> for braking systems at <acronym>
Automotive, an international supplier, <ed_verb> through congested <noun> on a
<adjective> freeway in <city> recently — without touching the <car_part> or
<car_part>— to demonstrate the Autocruise adaptive cruise-control system that
is in the new $<number> Volkswagen <proper_name>.
With a <adjective> unit hidden <preposition> the front bumper, the Phaeton
<adverb> adjusted to the speed of a <ing_verb> commuter ahead. Then, when
Mr. Cossins shifted to the next <noun>, the car accelerated <adverb> to its
<adjective> speed, <ing_verb> nimbly when a lawn-service truck <verb> into the flow."
Few questions, first in my while loop, the selection = raw_input will only run once like if i type in wrong the first time it will only run the erro thing once. Is there like a " else break" command for while loops? Second my nytimes string.. how can i make the whole paragraph one string? Lastly i still need a simpler way to implemet the inputed words with the ones in the text. Thanks Edit: please use [CODE] tags, this is particually important in Python! Last edited by netytan : December 5th, 2003 at 02:27 AM. |
|
#6
|
||||
|
||||
|
You might find a list useful:
Code:
>>> a = ["fred","tom","harry"] >>> b = "tom" >>> b in a True >>> b not in a False Grim |
|
#7
|
||||
|
||||
|
Big strings can be put between triple quotes:
''' anything here is a string until ''' Have a look at the string methods for search and replace. You could also read the string module documentation for hints. http://www.brunningonline.net/simon...html#BasicTypes Is a useful summary. ![]() |
|
#8
|
|||
|
|||
|
Heres another "shortcut" you might want to use that should make your item substitution automatic:
Code:
#!/usr/bin/python
noun1 = raw_input("noun: ")
verb1 = raw_input("verb: ")
noun2 = raw_input("another noun: ")
madlib = "%(noun1)s %(verb1)s over the %(noun2)s." % vars()
print madlib
Its basically an extension of string formatting: Code:
>>> n = "string" >>> print "This is a %s" % n ... This is a string In Python you can use a dictionary (which has named keys) for the automatic replacement. vars() is a dictionary containing all of your local variables (which would be all of your raw_inputs). Code:
>>> n = {}
>>> n["test"] = "blah"
>>> print "This is a %(test)s" % n
...
This is a blah
|
|
#9
|
||||
|
||||
|
Mmm, i'm a little comfused here
why write a program thats hard coded for a particular file, if that file changes you'd have to rewrite the program and that would be a real bummer!Anyway to show how this 'could' be done i've writen a little example which will work with a any (none binary) file and is a lot shorter than your gonna end up being.. You will of course have to tweek it so it does what you want but ![]() Code:
#!/usr/bin/env
from re import findall
lines = []
path = 'sample.txt'
try:
for line in file(path, 'r'):
for tag in findall('<.+?>', line):
line = line.replace(tag, raw_input('Replace %s with ' % tag))
#append the line including alterations to 'lines' before writing
#to a file (user prompted).
lines.append(line)
file(raw_input('Save file as '), 'w').writelines(lines)
except Exception, note: print note
where sample.txt looks like this: Code:
I am sample.txt, i need <noun1>, <verb1>, <verb2> and <ing1> to work. You should also note, i can use any name between less-than and more than operators i.e. <much better> Note: '''strings''' like this are called multi-line strings and you should probably use locals() instead of vars() since vars(object) simply defaults to locals() if you don't pass it an object.Mark. Last edited by netytan : December 5th, 2003 at 09:55 AM. |
|
#10
|
||||
|
||||
|
Quote:
and taking this one step further... >>> files = ['list', 'of','files'] >>> while raw_input('enter filename please ') not in files: continue enter filename please 1 enter filename please 2 enter filename please 3 enter filename please 4 enter filename please 5 enter filename please once i caught enter filename please a fish alive enter filename please oh enter filename please and enter filename please to enter filename please end enter filename please we enter filename please type enter filename please a enter filename please value enter filename please from enter filename please 'files' enter filename please enter filename please list >>> This is a little useless since you can't get the value from raw input so>>> filename = '' >>> while filename not in files: filename = raw_raw('enter filename please ') enter filename please 1 enter filename please 2 enter filename please 3 enter filename please 4 enter filename please 5 enter filename please files >>> There ya have it ![]() Mark Last edited by netytan : December 5th, 2003 at 09:39 AM. |
|
#11
|
|||
|
|||
|
Quote:
WOW thats great. I also went on with the idea of just using any generic madlib file insted of specific ones. I came up with this. Code:
import string
def find(str, ch, index): # This function finds how many opening brackets#
while index < len(str): #there are in the text which tells, how many variables is present.#
if str[index] == ch:
return index
index = index + 1
def countbrackets(str, ch):
bracketcounter = 0
index = 0
while index<len(str):
if str[index] == ch:
bracketcounter = bracketcounter + 1
index = index + 1
return bracketcounter
loopcounter=0
while loopcounter==0:
try:
file_selection= raw_input ("Please enter a filename to read:")
madlibopen= open(file_selection,"r")
loopcounter=1
except:
print "This file does not exist."
loopcounter=0
readmadlib=madlibopen.read()
madlibopen.close()
madlib=""
firstbracket=find(readmadlib, "<", 0)
insertwords=readmadlib[:firstbracket]
madlib=madlib+insertwords
lastbracket=find(readmadlib, ">", firstbracket)
insertwords=readmadlib[firstbracket +1:lastbracket]
insertwords= raw_input("Please enter a " + insertwords + ":")
madlib = madlib + insertwords
repeatnumber=countbrackets(readmadlib, "<")
loops=1
while loops<repeatnumber:
firstbracket=find(readmadlib, "<", lastbracket)
insertwords=readmadlib[lastbracket + 1:firstbracket]
madlib=madlib+insertwords
lastbracket=find(readmadlib, ">", firstbracket)
insertwords=readmadlib[firstbracket +1:lastbracket]
insertwords= raw_input("Please enter a " + insertwords + ":")
madlib = madlib + insertwords
loops=loops+1
filename = raw_input ("Enter a filename to save you madlib as ( Press enter not to save ):")
if filename=="":
print ""
print madlib
else:
outputfile = open(filename, "w")
outputfile.write(madlib)
outputfile.close()
print ""
print madlib
As you can see it is very long and wierd.. so i will try to change your code and input someof my stuff, since your is so much easier to exmplain, ( I have to write what every line does and why its there ) Thanks a BUNCH! Edit: Please use [CODE] tags! Last edited by netytan : December 6th, 2003 at 05:33 AM. |
|
#12
|
|||
|
|||
|
Ahh--cool, you let it read other files. You can still use the vars() trick with that using regex. Of course, if you already have yoru madlib files created, you won't want to do change them all. Its also easier for someone creating the file to remember how to type <thing> than %(thing)s.
If your find function you shouldn't use str as one of your variables--you end up overwriting the __builtin__ str(). You could also modify yoru find function a bit (forgive me if I'm duplicating something you did exactly--your code tags didn't take and I can't read the indentation in your script): Code:
>>> import re
>>> n = re.compile("<[^>]*>")
>>> q = "<this> here is some <stuff> <blah>"
>>> z = n.findall(q)
>>> z
['<this>', '<stuff>', '<blah>']
This is similar to what netyan posted, but using a compiled regex which is usually a wee bit faster on scripts that do a lot of processing/looping. You could then len(z) and do a for loop to do your replacements. Last edited by netytan : December 6th, 2003 at 05:37 AM. |
|
#13
|
||
|
|