[Tutor] Reg. Expressions Parenthesis
Hey guys, girls, hope everyone is doing well. Here's my question, when using Regular Expressions, the docs say when using parenthesis, it "captures" the data. This has got me confused (doesn't take much), can someone explain this to me, please?? Here's an example to use. It's kinda long, so, if you'd rather provide your own shorter ex, that'd be fine. Thanks for any help as always. From: [\w\s]+?<([\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4})> From: matches the literal text "From: " [\w\s]+? matches one or more consecutive word characters or space characters. The question mark makes the match non-greedy, so it will match as few characters as possible while still allowing the whole regular expression to match (in this case, it's probably not necessary, but it does make the match more efficient since the thing that comes immediately afterwards is not a word character or space character). < matches a literal less-than sign (opening angle bracket) The same regular expression you had before (without From: and without parenthesis) is now surrounded by parentheses. This makes it a capturing group, so you can call m.group(1) to get the text matched by that part of the regex. > matches a literal greater-than sign Thanks, Chris Kavanagh ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reg. Expressions Parenthesis
On Tue, Jan 17, 2012 at 3:07 AM, Chris Kavanagh wrote: > Hey guys, girls, hope everyone is doing well. > > Here's my question, when using Regular Expressions, the docs say when > using parenthesis, it "captures" the data. This has got me confused > (doesn't take much), can someone explain this to me, please?? > > Here's an example to use. It's kinda long, so, if you'd rather provide > your own shorter ex, that'd be fine. Thanks for any help as always. > Here's a quick example: import re data = 'Wayne Werner fake-phone: 501-555-1234, fake-SSN: 123-12-1234' parsed = re.search('([\d]{3})-([\d]{3}-[\d]{4})', data) print(parsed.group()) print(parsed.groups()) parsed = re.search('[\d]{3}-[\d]{3}-[\d]{4}', data) print(parsed.group()) print(parsed.groups()) You'll notice that you can access the individual clusters using the .groups() method. This makes capturing the individual groups pretty easy. Of course, capturing isn't just for storing the results. You can also use the captured group later on. Let's say, for some fictitious reason you want to find every letter that appears as a double in some data. If you were to do this the "brute force" way you'd pretty much have to do something like this: for i in range(len(data)-1): found = [] if data[i] == data[i+1]: if not data[i] in found: found.append(i) print(found) The regex OTOH looks like this: In [29]: data = 'aaabababbcacacceadbacdb' In [32]: parsed = re.findall(r'([a-z])\1', data) In [33]: parsed Out[33]: ['a', 'b', 'c'] Now, that example was super contrived and also simple. Very few real-world applications will be as simple as that one - usually you have much crazier specifications, like find every person who has blue eyes AND blue hair, but only if they're left handed. Assuming you had data that looked like this: NameEye ColorHair Color Handedness Favorite type of potato WayneBlue BrownDexter Mashed Sarah Blue Blonde SinisterSpam(?) Kane Green White Dexter None Kermit Blue Blue SinisterIdaho You could parse out the data using captures and backrefrences [1]. HTH, Wayne [1] In this situation, of course, regex is overkill. It's easier to just .split() and compare. But if you're parsing something really nasty like EDI then sometimes a regex is just the best way to go[2]. [2] When people start to understand regexes they're like the proverbial man who only has a hammer. As Jamie Zawinski said[3], "Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems." I've come across very few occasions that regexes were actually useful, and it's usually extracting very specifically formatted data (money, phone numbers, etc.) from copious amounts of text. I've not yet had a need to actually process words with it. Especially using Python. [3]http://regex.info/blog/2006-09-15/247 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Virtual pet cat program
I am trying to code a virtual pet cat program. Heres what I have come up with so far: #Pet cat program #the user chooses a cat of their choice; choosing attributes such as colour, name etc #the user then has to look after the cat and keep it alive #create a class for the cat class Cat(object): """A virtual pet cat""" def __init__(self, name, hunger = 5, boredom = 0, tiredness = 0): print("Meww!") self.name = name self.hunger = hunger self.boredom = boredom self.tiredness = tiredness def __str__(self): att = "Feline friend\n" att += "Name: " + self.name + "\n" if self.hunger >= 2: print("Your pet is hungry.") elif self.boredom >= 2: print("Your pet is bored.") elif self.tiredness >= 2: print("Your pet is tired.") return att def __pass_time(self): self.hunger += 1 self.boredom += 1 self.tiredness += 1 def eat(self, food = 5): print("Pu purrr!") self.hunger -= food if self.hunger < 0: self.hunger = 0 self.__pass_time() def play(self, fun = 5): print("Chirrup!") self.boredom -= fun if self.boredom < 0: self.boredom = 0 self.__pass_time() def rest(self, sleep = 5): print("...") self.tiredness -= sleep if self.tiredness < 0: self.tiredness = 0 self.__pass_time() #introduce and explain the program to the user input("Welcome to the pet cat simulation program. You will get the opportunity to look after a cat of choice. Press enter to begin.") #get the users chosen attributes for their cat name = input("Please enter a name for your cat: ") user_cat = Cat(name) #taking care of the cat loop choice = None while choice != "0": print("What would you like to do? (Enter 1 to feed the cat, enter 2 to play with the cat, enter 3 to leave the cat to rest or press 0 to exit the program.") choice = input(">") if choice == "1": user_cat.eat print(user_cat) elif choice == "2": user_cat.play print(user_cat) elif choice == "3": user_cat.rest print(user_cat) input("Press enter to exit...") ...Then I try to run the program: Welcome to the pet cat simulation program. You will get the opportunity to look after a cat of choice. Press enter to begin. Please enter a name for your cat: X Meww! What would you like to do? (Enter 1 to feed the cat, enter 2 to play with the cat, enter 3 to leave the cat to rest or press 0 to exit the program. >1 Your pet is hungry. Feline friend Name: X What would you like to do? (Enter 1 to feed the cat, enter 2 to play with the cat, enter 3 to leave the cat to rest or press 0 to exit the program. >1 Your pet is hungry. Feline friend Name: X What would you like to do? (Enter 1 to feed the cat, enter 2 to play with the cat, enter 3 to leave the cat to rest or press 0 to exit the program. >1 Your pet is hungry. Feline friend Name: X What would you like to do? (Enter 1 to feed the cat, enter 2 to play with the cat, enter 3 to leave the cat to rest or press 0 to exit the program. >1 Your pet is hungry. Feline friend Name: X What would you like to do? (Enter 1 to feed the cat, enter 2 to play with the cat, enter 3 to leave the cat to rest or press 0 to exit the program. >0 Press enter to exit... As you can see, no matter how many times I 'feed' the cat, its always hungry. Can someone please tell me why it wont update? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Virtual pet cat program
>As you can see, no matter how many times I 'feed' the cat, its always hungry. >Can someone please tell me why it wont update? >while choice != "0": >print("What would you like to do? (Enter 1 to feed the cat, enter 2 to > play with the cat, enter 3 to leave the cat to rest or press 0 to exit the > program.") >choice = input(">") >if choice == "1": >user_cat.eat >print(user_cat) >elif choice == "2": >user_cat.play >print(user_cat) >elif choice == "3": >user_cat.rest >print(user_cat) You are not calling the function, just referring to it. >>> user_cat.eat > You should be calling user_cat.eat() or user_cat.eat( 10 ) to actually perform the action you desire. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Class vs. instance
Hello! Here is another one. class A: def __init__(self, data): self.data = data print self.data I'm trying to understand this function-like syntax: A('foo').__init__(42) A(12).data What are we actually calling this way? Are there any other ways to get the same result? Cheers. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Class vs. instance
On 01/17/2012 09:13 PM, Stayvoid wrote: Hello! Here is another one. class A: def __init__(self, data): self.data = data print self.data I'm trying to understand this function-like syntax: A('foo').__init__(42) A(12).data What are we actually calling this way? Are there any other ways to get the same result? The first line creates an instance of class A, then immediately calls the method __init__() as though it were a normal function. It then discards the object. You should only call __init__() from within another class' __init__(). It's called automatically when an object is created; leave it at that. You also usually want to keep the instance around, and use it more than once. Otherwise you could just use ordinary functions and dispense with the confusion. A(12) creates an object, then you reference the data attribute of that object, then you throw them both out. Not much use there either. Try something like: obj= A(49) print obj.data obj2 = A("artichoke") obj.data = 99 print obj.data print obj2.data Two more things. Remove the print statement from methods like __init__(), unless it's just for debugging purposes. And add a base class of object to your class definition, so that a new-style class is created. When you get to more advanced usage, it'll make a difference, and you might as well use the version of class that'll still work in Python 3.x. class A(object): . -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Reg Ex Parentheses
Hey guys, girls, hope everyone is doing well. Here's my question, when using Regular Expressions, the docs say when using parenthesis, it "captures" the data. This has got me confused (doesn't take much), can someone explain this to me, please?? Here's an example to use. It's kinda long, so, if you'd rather provide your own shorter ex, that'd be fine. Thanks for any help as always. From: [\w\s]+?<([\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4})> From: matches the literal text "From: " [\w\s]+? matches one or more consecutive word characters or space characters. The question mark makes the match non-greedy, so it will match as few characters as possible while still allowing the whole regular expression to match (in this case, it's probably not necessary, but it does make the match more efficient since the thing that comes immediately afterwards is not a word character or space character). < matches a literal less-than sign (opening angle bracket) The same regular expression you had before (without From: and without parenthesis) is now surrounded by parentheses. This makes it a capturing group, so you can call m.group(1) to get the text matched by that part of the regex. > matches a literal greater-than sign Thanks, Chris Kavanagh ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor