Re: [Tutor] Extract strings from a text file
> There is a text file that looks like this: > > text text text Joseph > text text text text text text text text text text text > text text text text text text text text text text text > text text text text text text text text text text text > text text text text text text text text text text text > text text text text text text text text text text text > text text text text text text text text text text text > text text text text text text text text text text text > text text text Joseph Smith > text text text 1 > text text text 0 > > What I am trying to do is: > > 1. I need to extract the name and the full name from this text file. For > example: ( ID is Joseph & Full name is Joseph Smith). in addition to denis' suggestion of using regular expressions, you can also look at the xml.etree module and have ElementTree parse them into tags for you, so all you have to do is ask for the ID and "Full name" tags to get your data. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Class instance understanding = None
On Fri, Feb 27, 2009 at 6:06 AM, David wrote: > Hi Everyone, > I go through the archived [Tutor] mail list to find programs others have > tried to do. I found one that would keep track of a petty cash fund. please > point out my misunderstanding. > Here is what I started with; > > #!/usr/bin/python > > from reportlab.lib.normalDate import ND > #import cPickle as p > #import pprint > > today = ND() > > class Account: > def __init__(self, initial): > self.balance = initial > def deposit(self, amt): > self.balance = self.balance + amt > def withdraw(self, amt): > self.balance = self.balance - amt > def getbalance(self): > return self.balance > print 'The current date is: ', today.formatUS() > > > data = float('100.00') > a = Account(data) > p = a.getbalance() > print 'balance = ', p > remove_data = float('50.00') > w = a.withdraw(remove_data) > print "withdraw = ", w > add_data = float('50.00') > add = a.deposit(add_data) > print "deposit = ", add > > > results; > The current date is: 02/27/09 > balance = 100.0 > withdraw = None > deposit = None > > expected results; > The current date is: 02/27/09 > balance = 100.0 > withdraw = 50.0 > deposit = 100.0 A method only returns a value if you do so explicitly, that is, end it with return value That's what happens in getbalance: return self.balance deposit and withdraw however do not return a value. If, like you do, you still try to extract their return value, it gives None. There are two ways to resolve this. The first gets closer to what you are trying to do, but is considered less proper programming, because it mixes functions of methods. In it, you add the returns to the methods: class Account: def __init__(self, initial): self.balance = initial def deposit(self, amt): self.balance = self.balance + amt return self.balance def withdraw(self, amt): self.balance = self.balance - amt return self.balance def getbalance(self): return self.balance The more preferable method is to leave the class alone, and call getbalance by hand: data = float('100.00') a = Account(data) p = a.getbalance() print 'balance = ', p remove_data = float('50.00') a.withdraw(remove_data) w = a.getbalance() print "withdraw = ", w add_data = float('50.00') a.deposit(add_data) add = a.getbalance() print "deposit = ", add Some other things: 1. data = float('100.00') is unnecessarily clumsy - you can specify floats directly without creating a string first by doing data = 100.0 2. You are creating a lot of variables only to use them for the one and only time on the next line. That's not necessarily bad, it sometimes improves readability especially if a lot is being done (which can then be split up in more readable parts), but doing it this much mostly causes your coding to look more complicated than it actually is. I would either prefer something like this: data = 100.0 remove_data = 50.0 add_data = 50.0 # first all input-like elements, so I know where to go when I want to change something trivial a = Account(data) print 'balance = ',a.getbalance() a.withdraw(remove_data) print 'balance after withdraw = ',a.getbalance() a.deposit(add_data) print 'balance after deposit = ',a.getbalance() doing away with p, w and add, or the even shorter variant where data, remove_data and add_data are also removed: a = Account(100.0) print 'balance = ',a.getbalance() a.withdraw(50.0) print 'balance after withdraw = ',a.getbalance() a.deposit(50.0) print 'balance after deposit = ',a.getbalance() -- André Engels, andreeng...@gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] setting PYTHONPATH on mac
wrote how does one go about setting a PYTHON path environment variable on Mac OS X 10.4? Your subject asks about PYTHONPATH, your text asks about PATH. These are two different things. Which do you want to know about? PATH is how Unix (ie MacOS aka Darwin) finds your Python interpreter PYTHONPATH is how python finds modules to import i set up my .profile in the Terminal.app (UNIX) with a text file with the following line: PATH=$PATH:/Applications/Autodesk/maya8.5/Maya.app/Contents/bin They are both set that way but you need to export them to take effect outside .profile You can use: export PATH= export PYTHONPATH= or PATH= export PATH PYTHONPATH=... export PYTHONPATH You might find this page helpful http://club.mandriva.com/xwiki/bin/view/KB/BasicsBshell5 Or search the Apple help files there is a page there describing the use of bash and bash_profile settings. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] re Format a file
HelloFinally I managed to writ a function to format a file. Thank to everybody for their tips. def mmm(a): import os,textwrap so=open(a) d=os.path.dirname(a)+os.sep+'temp.txt' de=open(d,'w') import textwrap for line in so: if len(line)<70:de.write(line+'\n') if len(line)>70: da=textwrap.fill(line,width=60) de.write(da+'\n') so.close() de.close() Any improvements and suggestions are welcome. Thanks Prasad ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Extract strings from a text file
On Fri, Feb 27, 2009 at 2:59 AM, wesley chun wrote: > > There is a text file that looks like this: > > > > text text text Joseph > > text text text text text text text text text text text > > text text text text text text text text text text text > > text text text text text text text text text text text > > text text text text text text text text text text text > > text text text text text text text text text text text > > text text text text text text text text text text text > > text text text text text text text text text text text > > text text text Joseph Smith > > text text text 1 > > text text text 0 > > > > What I am trying to do is: > > > > 1. I need to extract the name and the full name from this text file. For > > example: ( ID is Joseph & Full name is Joseph Smith). > > > in addition to denis' suggestion of using regular expressions, you can > also look at the xml.etree module and have ElementTree parse them into > tags for you, so all you have to do is ask for the ID and "Full name" > tags to get your data. > > good luck! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > "Python Fundamentals", Prentice Hall, (c)2009 >http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Since I'm learning Pyparsing, this was a nice excercise. I've written this elementary script which does the job well in light of the data we have from pyparsing import * ID_TAG = Literal("") FULL_NAME_TAG1 = Literal("") END_TAG = Literal("', 'Joseph', '', 'Joseph', 'Smith', 'http://emnawfal.googlepages.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] re Format a file
"prasad rao" wrote for line in so: if len(line)<70:de.write(line+'\n') if len(line)>70: da=textwrap.fill(line,width=60) de.write(da+'\n') What happens if the line is exactly 70 characters long? I think you want an else instead of the second if -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Extract strings from a text file
On Fri, Feb 27, 2009 at 2:22 AM, spir wrote: > Anyway for a startup exploration you can use regular expressions (regex) to > extract individual data item. For instance: > > from re import compile as Pattern > pattern = Pattern(r""".*(.+)<.+>.*""") > line = "text text text Joseph" > print pattern.findall(line) > text = """\ > text text text Joseph > text text text Jodia > text text text Joobawap > """ > print pattern.findall(text) > ==> > ['Joseph'] > ['Joseph', 'Jodia', 'Joobawap'] You need to be a bit careful with wildcards, your regex doesn't work correctly if there are two s on a line: In [7]: re.findall(r""".*(.+)<.+>.*""", 'text JosephMary') Out[7]: ['Mary'] The problem is that the initial .* matches the whole line; the regex then backtracks to the second , finds a match and stops. Taking out the initial .* shows another problem: In [8]: re.findall(r"""(.+)<.+>""", 'text JosephMary') Out[8]: ['JosephMary'] Now (.+) is matching to the end of the line, then backing up to find the last <. One way to fix this is to use non-greedy matching: In [10]: re.findall(r"""(.+?)<""", 'text JosephMary') Out[10]: ['Joseph', 'Mary'] Another way is to specifically exclude the character you are matching from the wildcard match: In [11]: re.findall(r"""([^[<]+)<""", 'text JosephMary') Out[11]: ['Joseph', 'Mary'] Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing perimeters in dictionary values?
On 25/02/2009, Alan Gauld wrote: > > "nathan virgil" wrote > > > Whenever I try to use the talk method (which reports the mood, and doesn't > > take parameters), it says I gave it too many parameters. > > > > Sorry, I should have pointed out that you will need to redefine > all your functions to accept a parameter. > > Alan G > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Always makes me smile when (experienced) people redesign the wheel... >From the docs (http://www.python.org/doc/2.6/library/functools.html): "The partial() is used for partial function application which “freezes” some portion of a function’s arguments and/or keywords resulting in a new object with a simplified signature." -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Class instance understanding = None
Thank you spir and Andre for the explanation. You are very good teachers. I can now continue. I am sure I will be back. Next I am going to set up a menu to enter amounts and also a way to store the resulting balance. Is cPickle a good way to do this? -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Class instance understanding = None
Thank you spir and Andre for the explanation. You are very good teachers. I can now continue. I am sure I will be back. Next I am going to set up a menu to enter amounts and also a way to store the resulting balance. Is cPickle a good way to do this? -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] concatenating files
Hai, I have file1.dat,file2.dat...file 300.dat in one directory. I want to concatenate all the files in a single file (total.dat) with a string "END" separating the file contents. my total.dat should be file1.dat contents END file2.dat contents END file300.dat. now i have another 400 such *.dat files in another directory whose contents i hve to append to "total.dat", how can i do this task. i need to do something like, updating the file total.dat without overwritting it. Thanks, Bala ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Extract strings from a text file
Emad wrote: >>> Since I'm learning Pyparsing, this was a nice excercise. I've written this elementary script which does the job well in light of the data we have from pyparsing import * ID_TAG = Literal("") FULL_NAME_TAG1 = Literal("") END_TAG = Literal("', 'Joseph', '', 'Joseph', 'Smith', '>> Welcome to the world of pyparsing! Your program is a very good first cut at this problem. Let me add some suggestions (more like hints toward more advanced concepts in your pyparsing learning): - Look into Group, as in Group(OneOrMore(word)), this will add organization and structure to the returned results. - Results names will make it easier to access the separate parsed fields. - Check out the makeHTMLTags and makeXMLTags helper methods - these do more than just wrap angle brackets around a tag name, but also handle attributes in varying order, case variability, and (of course) varying whitespace - the OP didn't explicitly say this XML data, but the sample does look suspicious. If you only easy_install'ed pyparsing or used the binary windows installer, please go back to SourceForge and download the source .ZIP or tarball package - these have the full examples and htmldoc directories that the auto-installers omit. Good luck in your continued studies! -- Paul ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Extract strings from a text file
On Fri, Feb 27, 2009 at 10:01 AM, Paul McGuire wrote: > Emad wrote: > >>> > Since I'm learning Pyparsing, this was a nice excercise. I've written this > elementary script which does the job well in light of the data we have > > from pyparsing import * > ID_TAG = Literal("") > FULL_NAME_TAG1 = Literal(" FULL_NAME_TAG2 = Literal("name>") > END_TAG = Literal(" word = Word(alphas) > pattern1 = ID_TAG + word + END_TAG > pattern2 = FULL_NAME_TAG1 + FULL_NAME_TAG2 + OneOrMore(word) + END_TAG > result = pattern1 | pattern2 > > lines = open("lines.txt")# This is your file name > for line in lines: >myresult = result.searchString(line) >if myresult: >print myresult[0] > > > # This prints out > ['', 'Joseph', ' ['', 'Joseph', 'Smith', ' > # You can access the individual elements of the lists to pick whatever you > want > > Emad - > >>> > > Welcome to the world of pyparsing! Your program is a very good first cut > at > this problem. Let me add some suggestions (more like hints toward more > advanced concepts in your pyparsing learning): > - Look into Group, as in Group(OneOrMore(word)), this will add organization > and structure to the returned results. > - Results names will make it easier to access the separate parsed fields. > - Check out the makeHTMLTags and makeXMLTags helper methods - these do more > than just wrap angle brackets around a tag name, but also handle attributes > in varying order, case variability, and (of course) varying whitespace - > the > OP didn't explicitly say this XML data, but the sample does look > suspicious. > > If you only easy_install'ed pyparsing or used the binary windows installer, > please go back to SourceForge and download the source .ZIP or tarball > package - these have the full examples and htmldoc directories that the > auto-installers omit. > > Good luck in your continued studies! > -- Paul > > Thanks Paul. I've read lots ABOUT pyparsing, but doing is different. Programming is mostly fun just for fun for me. I'm a linguist surrounded by many programmers. I enjoy Python and Pyparsing a lot. -- لا أعرف مظلوما تواطأ الناس علي هضمه ولا زهدوا في إنصافه كالحقيقة.محمد الغزالي "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Class definition...
Your tutorial is awesome...thanks again... The biggest confusion I have just had is the self.balance kind of thing. I need to just remember how it is treating each individual statement is all. Remember how everything is basically an object...just wrapping my brain around it for the most part. On Thu, Feb 26, 2009 at 11:42 AM, Alan Gauld wrote: > > "Spencer Parker" wrote > > I am looking for a good tutorial to walk through that really explains >> class >> definition. This has been one sticking point that always messes me up >> > > I assume from that you have been through the basic tutors like mine? > > Have you tried the deeper material in Dive into Python and the official > tutorial? > > If so then it is probnably better for you to give us some specific > questions you have. Or post a bit of a tutorialyou don't understand > and we can collectively try to clarify it. Specific questions are always > easier to answer than generalities. > > the most part. That and when people use "self". For some reason I just >> can't grasp what people say. Any good pointers to throw at me? >> > > OK, I explain self in my OOP tutor topic ( a sub heading under > "Using Classes"), but again if thats not sufficient then you probably > need to give us explicit examples of what you don't understand and > your concerns. > > HTH, > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Add elements to list and display it [Very newbie question]
I am beggining to learn Python and I appreciate if you help me with this: "I want a piece of a program to request the user to input "elements" (numbers, text, etc) and store them into a list. Then, I want to display all the elements one-per-line." I started using this code: #!/usr/bin/env python # # This function fills any given list # and display its content. # x = 0 # Variable "x" initiallized to zero, just because Python required it while (x != 't2' ): # On user's input "t2", no more input must be required list = []# I start a zero-elements list x = raw_input('Enter your number or text: ')# Software asks for user's input. list.append(x) # User's input is append to the list "list" for x in list: # It asks to enter the list and... print x # print their elements. Unfortunately, this code fails to do what I expect. I notice that user's input is not being append to the list, so, when I require to print the elements of the list only "t2" is displayed. I don't know how to append elements to a list on user's input. I appreciate your clearence. Regards, Will. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Add elements to list and display it [Very newbie question]
Le Fri, 27 Feb 2009 11:19:50 -0600, Network Administrator s'exprima ainsi: > I am beggining to learn Python and I appreciate if you help me with this: > > "I want a piece of a program to request the user to input "elements" > (numbers, text, etc) and store them into a list. Then, I want to display all > the elements one-per-line." > > I started using this code: > > #!/usr/bin/env python > # > # This function fills any given list > # and display its content. > # > x = 0 # Variable "x" initiallized to zero, just > because Python required it > while (x != 't2' ): # On user's input "t2", no more input must be > required > list = []# I start a zero-elements list > x = raw_input('Enter your number or text: ')# Software > asks for user's input. > > list.append(x) > # User's input is append to the list "list" > > for x in list: # It asks to enter the list and... > print x # print their elements. > > Unfortunately, this code fails to do what I expect. I notice that user's > input is not being append to the list, so, when I require to print the > elements of the list only "t2" is displayed. I don't know how to append > elements to a list on user's input. Hello Will, Just watch the algorithm you designed for the task -- pretty sure you will find the issue yourself: -0- init a variable that will store individual input === enter a loop -- will be quit on "flag" input -1- set input list empty -2- get user input -3- append it to the list -4- print list An additional question: should 't2' be stored into the list? denis -- la vita e estrany ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Class instance understanding = None
Andre Engels wrote: The more preferable method is to leave the class alone, and call getbalance by hand: data = float('100.00') a = Account(data) p = a.getbalance() print 'balance = ', p remove_data = float('50.00') a.withdraw(remove_data) w = a.getbalance() print "withdraw = ", w add_data = float('50.00') a.deposit(add_data) add = a.getbalance() print "deposit = ", add Some other things: 1. data = float('100.00') is unnecessarily clumsy - you can specify floats directly without creating a string first by doing data = 100.0 2. You are creating a lot of variables only to use them for the one and only time on the next line. That's not necessarily bad, it sometimes improves readability especially if a lot is being done (which can then be split up in more readable parts), but doing it this much mostly causes your coding to look more complicated than it actually is. I would either prefer something like this: data = 100.0 remove_data = 50.0 add_data = 50.0# first all input-like elements, so I know where to go when I want to change something trivial a = Account(data) print 'balance = ',a.getbalance() a.withdraw(remove_data) print 'balance after withdraw = ',a.getbalance() a.deposit(add_data) print 'balance after deposit = ',a.getbalance() doing away with p, w and add, or the even shorter variant where data, remove_data and add_data are also removed: a = Account(100.0) print 'balance = ',a.getbalance() a.withdraw(50.0) print 'balance after withdraw = ',a.getbalance() a.deposit(50.0) print 'balance after deposit = ',a.getbalance() Ok almost there, here is what i have now; http://linuxcrazy.pastebin.com/m6b090d2d My problem now is the balance is updated from the file that is pickled fine, but the first entry goes is not added to that total. I know it is in this part; start_total() start = 0 a = Account(start) but when I change it to; start_total() start = start_total() a = Account(start) here is the error; Enter Amount: 100 Traceback (most recent call last): File "./py_pettycash.py", line 77, in menu() File "./py_pettycash.py", line 53, in menu a.deposit(cash) File "./py_pettycash.py", line 15, in deposit self.balance = self.balance + amt TypeError: unsupported operand type(s) for +: 'NoneType' and 'Decimal' -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] concatenating files
Bala subramanian wrote: Hai, I have file1.dat,file2.dat...file 300.dat in one directory. I want to concatenate all the files in a single file (total.dat) with a string "END" separating the file contents. my total.dat should be file1.dat contents END file2.dat contents END file300.dat. now i have another 400 such *.dat files in another directory whose contents i hve to append to "total.dat", how can i do this task. i need to do something like, updating the file total.dat without overwritting it. Thanks, Bala This should about do it: - #!/usr/bin/env python import sys , os , glob startDir = '' totalFile = '/path/to/total.dat' if len(sys.argv) > 1 and os.path.isdir(sys.argv[1]): startDir = sys.argv[1] else: print 'Usage: %s ' % os.path.basename(sys.argv[0]) sys.exit(1) tfh = open(totalFile , 'a') for f in glob.glob(os.path.join(startDir , '*.dat')): tfh.write('%s contents\n' % f) tfh.write(open(f).read()) tfh.write('\nEND\n') tfh.close() - All you have to do is set "totalFile" to your main output file and then call the script as "scriptname.py /path/to/datfile/directory". -- Jay Deiman \033:wq! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Class instance understanding = None
David wrote: but when I change it to; start_total() start = start_total() a = Account(start) here is the error; Enter Amount: 100 Traceback (most recent call last): File "./py_pettycash.py", line 77, in menu() File "./py_pettycash.py", line 53, in menu a.deposit(cash) File "./py_pettycash.py", line 15, in deposit self.balance = self.balance + amt TypeError: unsupported operand type(s) for +: 'NoneType' and 'Decimal' -david Ok I got it, same problem I had before no return :) def start_total(): fname = open("cash.dat", "r") contents = cPickle.Unpickler(fname) data = contents.load() print "The current balance is", data fname.close() return data start = start_total() a = Account(start) Thanks all, any other comments?, I am going to add some error checking but, I am so happy, woopee -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Auto Refresh
I am trying to read a value in a variable from a different class every time I click on a refresh button for my GUI program. The problem is I am using statictext so when I refresh, it displays the new value on top of the old one. In my main GUI: def refresh(self, event): x = refresh_var() value = wx.StaticText(self, -1, str(x.var_rate)) In my refresh class: class refresh_var(): def var_rate(self): random_var = random.randint(5, 100) return random_var So each time I click on the button, which runs refresh, the new value generated by random.randint will be on top of the old number. Is there any commands I can use to remove the old value that is on the GUI window before I put the new one on there? Or is there a better command/syntax that does the same job? I am ultimately trying to make it so the GUI program refreshes and rereads random_var on a set interval. Can anyone offer any advice on how to do it or any commands I can read up on the Internet? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Class definition...
>> I am looking for a good tutorial to walk through that really explains class >> definition. > > I assume from that you have been through the basic tutors like mine? >: > OK, I explain self in my OOP tutor topic ( a sub heading under > "Using Classes"), but again if thats not sufficient then you probably > need to give us explicit examples of what you don't understand and > your concerns. similarly, i go through a deep and comprehensive treatment of all aspects of object-oriented programming in Python, from the highest-level intro all the way through metaclasses in the OOP chapter (13) of Core Python (see below). when you're beyond alan's great tutorial as well as mark's dive, i hope you'll find Core Python a useful resource to putting it all together. best of luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Not Storing State
Hi, This is both a general question and a specific one. I want to iterate over a bunch of lines; If any line contains a certain string, I want to do something, otherwise do something else. I can store state - eg line 1 - did it contain the string? no.. ok we're cool, next line But, I'd like to avoid keeping state. How can I do this? S. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] re Format a file
On Fri, Feb 27, 2009 at 5:09 AM, prasad rao wrote: > Hello > Finally I managed to writ a function to format a file. > Thank to everybody for their tips. > > def mmm(a): > import os,textwrap > so=open(a) > d=os.path.dirname(a)+os.sep+'temp.txt' > de=open(d,'w') > import textwrap > for line in so: > if len(line)<70:de.write(line+'\n') You are introducing an extra newline here, line already ends in a newline. > if len(line)>70: > da=textwrap.fill(line,width=60) > de.write(da+'\n') Not sure if textwrap strips the trailing newline, if not, this is also double-spacing. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Convert a string of numbers to a list
Turns out I was close but had not combined everything. I never would have picked up on the map() function. Much more efficient than looping through the whole mess and converting to int. x = ['[335, 180, 201, 241, 199]\r\n'] y = map( int, x[0].strip( '[]\r\n' ).split( ', ' ) ) #need an index here print y [335, 180, 201, 241, 199] Thanks for your help! kbk Kent Johnson wrote: For one line: In [11]: s = '[335, 180, 201, 241, 199]\r\n' In [12]: map(int, s.strip('[]\r\n').split(', ')) Out[12]: [335, 180, 201, 241, 199] Modify appropriately to handle a list of lines. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing perimeters in dictionary values?
"Richard Lovely" wrote > Sorry, I should have pointed out that you will need to redefine > all your functions to accept a parameter. Always makes me smile when (experienced) people redesign the wheel... From the docs (http://www.python.org/doc/2.6/library/functools.html): "The partial() is used for partial function application which “freezes” some portion of a function’s arguments and/or keywords resulting in a new object with a simplified signature." I'm not sure how you would use partial in this case, I still think you'd need to add a parameter to the function definitions. partial would remove the need for lambda in some of the other solutions though. But an interesting module that I've not seen before. Although since it was only introduced in 2.5 I'm not surprised, I've been focussing more on v3 lately rather than the new stuff in 2.5/2.6 (in fact I don't even have 2.6 loaded yet and only have 2.5 on one PC...) Thanks for highlighting it. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] concatenating files
"Bala subramanian" wrote I have file1.dat,file2.dat...file 300.dat in one directory. I want to concatenate all the files in a single file (total.dat) with a string "END" separating the file contents. my total.dat should be file1.dat contents END file2.dat contents END file300.dat. now i have another 400 such *.dat files in another directory whose contents i hve to append to "total.dat", how can i do this task. i need to do something like, updating the file total.dat without overwritting it. Thanks, Bala ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] concatenating files
"Bala subramanian" wrote I have file1.dat,file2.dat...file 300.dat in one directory. I want to concatenate all the files in a single file (total.dat) with a string "END" separating the file contents. If you are on Linux (or other *nix variant) you may be better off using the shell... for f in *.dat do cat $f >> total.dat echo "END" >> total.dat done Will do it for you. If you are on Windoze then you need to write a batch file and then execute it within the for loop so I'd just stick with Python there. (Or install cygwin :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Auto Refresh
"Hi" wrote In my main GUI: def refresh(self, event): x = refresh_var() value = wx.StaticText(self, -1, str(x.var_rate)) Its not clear how you are positioning Static Text, I suspect you need it as a opart of your main GUI and then reference it in here and use the SetLabel() method to update its contents. But I also not that you are not calling the var_rate method of x. Or does your code really look like value = wx.StaticText(self, -1, str(x.var_rate())) Notice the extra parens... So each time I click on the button, which runs refresh, the new value generated by random.randint will be on top of the old number. Is there any commands I can use to remove the old value that is on the GUI window before I put the new one on there? I think you can just update the content of the original Text widget using SetLabel() -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Not Storing State
"Stephen Nelson-Smith" wrote I want to iterate over a bunch of lines; for line in If any line contains a certain string, I want to do something, otherwise do something else. if in line: doSomething() else: doSomethingElse() I can store state - eg line 1 - did it contain the string? no.. ok we're cool, next line No need, just translate what you asked into Python code directly. You don't say what kind of "bunch" your lines are in but the above will work with an open file or a list or a tuple etc. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Convert a string of numbers to a list
Kyle Kwaiser wrote: x = ['[335, 180, 201, 241, 199]\r\n'] y = map( int, x[0].strip( '[]\r\n' ).split( ', ' ) ) #need an index here print y [335, 180, 201, 241, 199] I realize it's not totally secure, but if your string really is in that format (i.e., a representation of a list), you COULD just use eval(): >>> x = '[335, 180, 201, 241, 199]\r\n' >>> y = eval(x.strip()) >>> print y [335, 180, 201, 241, 199] >>> Regards, Vern Ceder ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] new print statement + time module
I downloaded python 3.0.1 today and started experimenting with the new print statement. >>>import time >>>for l in 'the answer': ...print(l,end='') ...time.sleep(0.1) the code is supposed to print "the answer" with a 0.1 second long pause between the letters. instead, it waits for 1 second ( 0.1*len("the answer") seconds ) and then prints "the answer". what am I doing wrong ? both replacing print(l,end='') with print(l) or using the msvcrt module instead of the print function work fine. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] new print statement + time module
Le Sat, 28 Feb 2009 06:34:07 +0200, George Wahid s'exprima ainsi: > I downloaded python 3.0.1 today and started experimenting with the new > print statement. > > >>>import time > >>>for l in 'the answer': > ...print(l,end='') > ...time.sleep(0.1) > > the code is supposed to print "the answer" with a 0.1 second long > pause between the letters. instead, it waits for 1 second ( > 0.1*len("the answer") seconds ) and then prints "the answer". what am > I doing wrong ? Indeed, it does the same for me with python 2.5: from time import sleep for c in "1234567890": sleep(0.25) print c, I guess python underlying outputs are managed like a queue that is flushed at certain points, eg whan a newline comes. Already noticed weird outputs messing up ordinary prints (~ sys.stdout) and exceptions messages (sys.stderr). I'd like to know more about that. > both replacing print(l,end='') with print(l) or using the msvcrt > module instead of the print function work fine. The same with py2.5. Without the ',', all is fine. Maybe there is a trick to force python printing ot in due time, but I have no idea, sorry. Denis -- la vita e estrany ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Add elements to list and display it [Very newbie question]
Here is one possible implementation of your project. *Code:* #Dont use list as a variable name, its one of the reserved words. mylist = [] #realize any values captured here are strings x = raw_input('Enter num or text: ') mylist.append(x) x = raw_input('Enter num or text: ') mylist.append(x) #output the type of objects you've entered (hint: they'll always be strings.. ;) print type(mylist[0]) print type(mylist[1]) #print the list of items for i in mylist: print i *When you run the program:* Enter num or text: 27 Enter num or text: Eric 27 Eric On Fri, Feb 27, 2009 at 10:19 AM, Network Administrator < administrador.de@gmail.com> wrote: > I am beggining to learn Python and I appreciate if you help me with this: > > "I want a piece of a program to request the user to input "elements" > (numbers, text, etc) and store them into a list. Then, I want to display all > the elements one-per-line." > > I started using this code: > > #!/usr/bin/env python > # > # This function fills any given list > # and display its content. > # > x = 0 # Variable "x" initiallized to zero, just > because Python required it > while (x != 't2' ): # On user's input "t2", no more input must be > required > list = []# I start a zero-elements list > x = raw_input('Enter your number or text: ')# Software > asks for user's input. > > list.append(x) > # User's input is append to the list "list" > > for x in list: # It asks to enter the list and... > print x # print their elements. > > Unfortunately, this code fails to do what I expect. I notice that user's > input is not being append to the list, so, when I require to print the > elements of the list only "t2" is displayed. I don't know how to append > elements to a list on user's input. > > I appreciate your clearence. > > Regards, > > > Will. > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] new print statement + time module
"spir" wrote in message news:20090228081629.36a24...@o... Le Sat, 28 Feb 2009 06:34:07 +0200, George Wahid s'exprima ainsi: I downloaded python 3.0.1 today and started experimenting with the new print statement. >>>import time >>>for l in 'the answer': ...print(l,end='') ...time.sleep(0.1) the code is supposed to print "the answer" with a 0.1 second long pause between the letters. instead, it waits for 1 second ( 0.1*len("the answer") seconds ) and then prints "the answer". what am I doing wrong ? Indeed, it does the same for me with python 2.5: from time import sleep for c in "1234567890": sleep(0.25) print c, I guess python underlying outputs are managed like a queue that is flushed at certain points, eg whan a newline comes. Already noticed weird outputs messing up ordinary prints (~ sys.stdout) and exceptions messages (sys.stderr). I'd like to know more about that. both replacing print(l,end='') with print(l) or using the msvcrt module instead of the print function work fine. The same with py2.5. Without the ',', all is fine. Maybe there is a trick to force python printing ot in due time, but I have no idea, sorry. stdout is line-buffered. Here's the trick: import time import sys for l in 'the answer': print(l,end='') sys.stdout.flush() time.sleep(0.1) -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor