Python Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me
Go Back   Dev Shed ForumsProgramming LanguagesPython Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
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  
Old December 4th, 2003, 01:16 PM
SuperDude SuperDude is offline
Junior Member
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2003
Posts: 4 SuperDude User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
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

Reply With Quote
  #2  
Old December 4th, 2003, 03:02 PM
telex4's Avatar
telex4 telex4 is offline
Wacky hack
Dev Shed Novice (500 - 999 posts)
 
Join Date: Apr 2001
Location: London, England
Posts: 512 telex4 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 25 m 29 sec
Reputation Power: 8
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.

Reply With Quote
  #3  
Old December 4th, 2003, 05:19 PM
netytan's Avatar
netytan netytan is offline
Hello World :)
Dev Shed Frequenter (2500 - 2999 posts)
 
Join Date: Mar 2003
Location: Hull, UK
Posts: 2,529 netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level) 
Time spent in forums: 1 Week 2 Days 17 h 19 m 5 sec
Reputation Power: 63
Send a message via ICQ to netytan Send a message via AIM to netytan Send a message via MSN to netytan Send a message via Yahoo to netytan
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.
__________________
programming language development: www.netytan.com Hula


Reply With Quote
  #4  
Old December 4th, 2003, 06:15 PM
SuperDude SuperDude is offline
Junior Member
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2003
Posts: 4 SuperDude User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
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 ...

Reply With Quote
  #5  
Old December 4th, 2003, 06:58 PM
SuperDude SuperDude is offline
Junior Member
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2003
Posts: 4 SuperDude User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
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.

Reply With Quote
  #6  
Old December 5th, 2003, 05:09 AM
Grim Archon's Avatar
Grim Archon Grim Archon is offline
Mini me.
Dev Shed Novice (500 - 999 posts)
 
Join Date: Nov 2003
Location: Cambridge, UK
Posts: 783 Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)  Folding Points: 1488 Folding Title: Novice Folder
Time spent in forums: 3 Days 2 h 15 m 57 sec
Reputation Power: 7
Send a message via MSN to Grim Archon
You might find a list useful:
Code:
>>> a = ["fred","tom","harry"]
>>> b = "tom"
>>> b in a
True
>>> b not in a
False


Grim

Reply With Quote
  #7  
Old December 5th, 2003, 05:23 AM
Grim Archon's Avatar
Grim Archon Grim Archon is offline
Mini me.
Dev Shed Novice (500 - 999 posts)
 
Join Date: Nov 2003
Location: Cambridge, UK
Posts: 783 Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)  Folding Points: 1488 Folding Title: Novice Folder
Time spent in forums: 3 Days 2 h 15 m 57 sec
Reputation Power: 7
Send a message via MSN to Grim Archon
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.


Reply With Quote
  #8  
Old December 5th, 2003, 07:50 AM
oxygenthief oxygenthief is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2003
Posts: 35 oxygenthief User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 5
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

Reply With Quote
  #9  
Old December 5th, 2003, 09:27 AM
netytan's Avatar
netytan netytan is offline
Hello World :)
Dev Shed Frequenter (2500 - 2999 posts)
 
Join Date: Mar 2003
Location: Hull, UK
Posts: 2,529 netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level) 
Time spent in forums: 1 Week 2 Days 17 h 19 m 5 sec
Reputation Power: 63
Send a message via ICQ to netytan Send a message via AIM to netytan Send a message via MSN to netytan Send a message via Yahoo to netytan
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.

Reply With Quote
  #10  
Old December 5th, 2003, 09:34 AM
netytan's Avatar
netytan netytan is offline
Hello World :)
Dev Shed Frequenter (2500 - 2999 posts)
 
Join Date: Mar 2003
Location: Hull, UK
Posts: 2,529 netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level) 
Time spent in forums: 1 Week 2 Days 17 h 19 m 5 sec
Reputation Power: 63
Send a message via ICQ to netytan Send a message via AIM to netytan Send a message via MSN to netytan Send a message via Yahoo to netytan
Quote:
Originally posted by Grim Archon
You might find a list useful:
Code:
>>> a = ["fred","tom","harry"]
>>> b = "tom"
>>> b in a
True
>>> b not in a
False


Grim


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.

Reply With Quote
  #11  
Old December 5th, 2003, 09:38 PM
SuperDude SuperDude is offline
Junior Member
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2003
Posts: 4 SuperDude User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Quote:
Originally posted by netytan
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.


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.

Reply With Quote
  #12  
Old December 5th, 2003, 10:31 PM
oxygenthief oxygenthief is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2003
Posts: 35 oxygenthief User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 5
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.

Reply With Quote
  #13  
Old December 6th, 2003, 06:22 AM
netytan's Avatar
netytan netytan is offline