Re: [Tutor] question about manipulate images!
Hi. Try to find a tutorial on the steps to achieve such effect in a graphic program. Then map it to the scrpting steps to do the same with pil, python for gimp, for inkscape or simply Imagemagick. On 2011-01-17 8:37 AM, "zhengqing gan" wrote: Hi, Thanks for the reply. But I found that there are some website which can convert images into iphone icon style images, there should be an kind of algorithm to manipulate. Thanks! On Mon, Jan 17, 2011 at 3:33 AM, Elwin Estle wrote: > > > --- On Sun,... ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] how to extract data only after a certain condition is met
The other day I was writing a script to extract data from a file from the line where a text is found to the end of the file. The same functionality is this sed script: '1,/regexp/'d I couldn't put my head to work around this and came up with a solution using list slicing. But how can I do that? I was experimenting with a simple list and I came up with this. I wonder if I shouldn't you a "while" statement, but how? a = ['m', 'a', 'r', 'i', 'g', 'o', 'l', 'd'] b = True for letter in a: if letter != 'i' and b: continue elif letter == 'i': b = False else: print letter Ok. This works, but I wonder if I shouldn't you a "while" statement, but how? Of course this solution is simpler: extracted = a[a.index("i")+1:] But I didn't want to build a list in memory with "readlines()" in the case of a file. Thanks for your guidance, Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] quick speed question
On Thu, Sep 16, 2010 at 1:16 AM, Evert Rol wrote: > The latter: they are not the same: > d = {'key': 'food'} d['key'] == 'foo' > False 'foo' in d['key'] > True > > > Btw, generally don't use a reserved Python word for a variable, such as dict > in this case (I know it's an example, but it's still unsafe practice). > If you want to find out if 'foo' is a key, you can do: 'foo' in d, which will return False. I'm not sure, but if I recall this can even be faster than using the if. Regards, Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Lost in the control flow
On Fri, Aug 13, 2010 at 2:38 PM, Adam Bark wrote: > On 11/08/10 18:14, Eduardo Vieira wrote: > > On Tue, Aug 10, 2010 at 1:56 PM, Adam Bark wrote: > > > > The problem is you don't call make_dict unless there's a "FUEL SURCHARGE" or > multiple pins. Also you don't add the first pin to mydict["tracking"] unless > there's a "FUEL SURCHARGE". > > HTH, > Adam. > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > Hi, I made these changes, got rid of the functions, and changed some logic: > here is the link: http://pastebin.com/F19vKUjr > > Now mydict will be changing, of course with every loop, as the output below: > {'company': 'CITY SIGNS', 'tracking': ['600775301143'], 'id': '1'} > {'city': 'MEDICINE HAT', 'company': 'CITY SIGNS', 'tracking': > ['600775301143'], 'id': '1', 'prov': 'AB'} > {'city': 'MEDICINE HAT', 'company': 'TRIMLINE', 'tracking': > ['600775301150'], 'id': '2', 'prov': 'AB'} > {'city': 'ROCKY MOUNTAIN HOUSE', 'company': 'TRIMLINE', 'tracking': > ['600775301150'], 'id': '2', 'prov': 'AB'} > {'city': 'ROCKY MOUNTAIN HOUSE', 'company': 'TS SIGNS PRINTING & > PROMO', 'tracking': ['600775301168'], 'id': '3', 'prov': 'AB'} > {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', > 'tracking': ['600775301168'], 'id': '3', 'prov': 'AB'} > {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', > 'tracking': ['600775301168', '600775301168'], 'id': '3', 'prov': 'AB'} > {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', > 'tracking': ['600775301168', '600775301168', '600775301176'], 'id': > '3', 'prov': 'AB'} > {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', > 'tracking': ['600775301168', '600775301168', '600775301176', > '600775301184'], 'id': '3', 'prov': 'AB'} > {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', > 'tracking': ['600775301168', '600775301168', '600775301176', > '600775301184', '600775301192'], 'id': '3', 'prov': 'AB'} > {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', > 'tracking': ['600775301168', '600775301168', '600775301176', > '600775301184', '600775301192', '600775301200'], 'id': '3', 'prov': > 'AB'} > so I appended everything to a bigdata list and used it to update the > dictionary data_dict > > I can't understand why I get only one value: > {'18': {'city': 'ESTEVAN', > 'company': 'BRAKE & DRIVE SYSTEMS', > 'id': '18', > 'prov': 'SK', > 'tracking': ['600775301515', '600775301515', '600775301523']}} > > Regards, > > Eduardo > > > It looks to me like you keep overwriting the previous data, you keep using > mydict. Doing an append does not copy the dictionary it just copies a > reference to the underlying data structure. > Thank you, Adam. That was the problem. By using deepcopy I managed to fix it: final = deepcopy(mydict) Cheers, Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Lost in the control flow
On Tue, Aug 10, 2010 at 1:56 PM, Adam Bark wrote: > > The problem is you don't call make_dict unless there's a "FUEL SURCHARGE" or > multiple pins. Also you don't add the first pin to mydict["tracking"] unless > there's a "FUEL SURCHARGE". > > HTH, > Adam. > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Hi, I made these changes, got rid of the functions, and changed some logic: here is the link: http://pastebin.com/F19vKUjr Now mydict will be changing, of course with every loop, as the output below: {'company': 'CITY SIGNS', 'tracking': ['600775301143'], 'id': '1'} {'city': 'MEDICINE HAT', 'company': 'CITY SIGNS', 'tracking': ['600775301143'], 'id': '1', 'prov': 'AB'} {'city': 'MEDICINE HAT', 'company': 'TRIMLINE', 'tracking': ['600775301150'], 'id': '2', 'prov': 'AB'} {'city': 'ROCKY MOUNTAIN HOUSE', 'company': 'TRIMLINE', 'tracking': ['600775301150'], 'id': '2', 'prov': 'AB'} {'city': 'ROCKY MOUNTAIN HOUSE', 'company': 'TS SIGNS PRINTING & PROMO', 'tracking': ['600775301168'], 'id': '3', 'prov': 'AB'} {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', 'tracking': ['600775301168'], 'id': '3', 'prov': 'AB'} {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', 'tracking': ['600775301168', '600775301168'], 'id': '3', 'prov': 'AB'} {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', 'tracking': ['600775301168', '600775301168', '600775301176'], 'id': '3', 'prov': 'AB'} {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', 'tracking': ['600775301168', '600775301168', '600775301176', '600775301184'], 'id': '3', 'prov': 'AB'} {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', 'tracking': ['600775301168', '600775301168', '600775301176', '600775301184', '600775301192'], 'id': '3', 'prov': 'AB'} {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', 'tracking': ['600775301168', '600775301168', '600775301176', '600775301184', '600775301192', '600775301200'], 'id': '3', 'prov': 'AB'} so I appended everything to a bigdata list and used it to update the dictionary data_dict I can't understand why I get only one value: {'18': {'city': 'ESTEVAN', 'company': 'BRAKE & DRIVE SYSTEMS', 'id': '18', 'prov': 'SK', 'tracking': ['600775301515', '600775301515', '600775301523']}} Regards, Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Lost in the control flow
Hello, list! I'm trying to parse a text file. I'm getting confuse with my strategy, and flags or how to use a sequence of ifs or elifs, continue, etc. Anyhow, after several experiments this is close to what I'd like to get, except, I can't find a way to include all the pin numbers (12 number sequence): Here is my code: http://pastebin.com/1ps6WdF4 The example file is this: http://pastebin.com/1MZmE4d3 Basically, as a initial step, I'd like to transform this: 17 600775301465 CAREYON SIGNS & GRAPHICS EXP 5 93.00 $0.00 $ 26.77 RED DEER AB T4N1L2 FUEL SURCHARGE:2.10 GST/HST:1.44 600775301465 18.60 600775301473 18.60 600775301481 18.60 into this. View the code and file for details, please: {'city': 'AB', 'company': 'CAREYON SIGNS & GRAPHICS', 'tracking': ['600775301465', '600775301473', '600775301481', ], 'id': '17'} The way the code is working now I only get this: {'city': 'AB', 'company': 'CAREYON SIGNS & GRAPHICS', 'tracking': ['600775301465', '600775301465'], 'id': '17'}, and a only the ones that have multiple pin numbers. I'd appreciate your help. Thanks. Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Formatting date/time
On Wed, Aug 4, 2010 at 12:45 PM, Eric Hamiter wrote: > There are a few solutions here: > > http://stackoverflow.com/questions/904928/python-strftime-date-decimal-remove-0 > > Eric > > > On Wed, Aug 4, 2010 at 1:30 PM, Eduardo Vieira > wrote: >> >> I'm trying this example from python docs: >> from time import gmtime, strftime >> strftime("%a, %d %b %Y %H:%M:%S +", gmtime()) >> >> Output = 'Wed, 04 Aug 2010 17:58:42 +' >> Is not there a string formatting option for the day without a leading >> zero? Like: 'Wed, 4 Aug 2010 17:58:42 +' >> >> It looks like it's not in the docs. >> >> Thanks >> >> Eduardo >> ___ >> Tutor maillist - tu...@python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > Thank you for the link. Just what I needed to know. The option %e didn't work for me, but I will use the other suggestions in the answers. Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Formatting date/time
I'm trying this example from python docs: from time import gmtime, strftime strftime("%a, %d %b %Y %H:%M:%S +", gmtime()) Output = 'Wed, 04 Aug 2010 17:58:42 +' Is not there a string formatting option for the day without a leading zero? Like: 'Wed, 4 Aug 2010 17:58:42 +' It looks like it's not in the docs. Thanks Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] differences between mmap and StringIO
Hello, I'm getting confused about the usage of those 2 modules. Which should I use one to get/manipulate data from a text file? Regards, Eduardo www.express-sign-supply.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Advice on math
Hello, I've enjoying learning python for the first few years, and appreciate all the help I have received from this list. I had some interest in programming and am very glad to have made python my choice of programming language. Since I didn't go to college for computer studies, I feel my math is kind of rusty in some areas, and looks like improving/regaining math skills would help a lot in programming, logic, algorithms, etc. Right now I think I need a better understanding of logarithm, arrays (matrixes), and even probability. What links would you all recommend that would be useful for me to learn these things in a newbie-friendly way? With thankfulness, Eduardo www.expresssignproducts.com www.express-sign-supply.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] large file
> Thanks for this thread. This is very helful. I'm learning a lot from you > guys. :) > > - > [url=http://crosspromotion.wizard4u.com/]joint ventures[/url] > > -- > View this message in context: > http://old.nabble.com/-Tutor--large-file-tp28874185p28878191.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I think this subscriber is just spamming. Two post with the same text. Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] plain text to HTML parser
On Wed, Mar 17, 2010 at 1:11 PM, Azhagu Selvan wrote: > Hi, > > I want to get a formatted plaintext and convert into HTML like what > markdown does. I tried python-mardown. Is there any similar python > libraries to do that parsing?? > > -- Azhagu Selvan > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Hello, what do you mean by "formatted"? Markdown is a simple markup language, and there are several converters for it. What do you need that python markdown or Restructured Text wouldn't suit? Regards, Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running PIL.Image on .svg file
On Tue, Feb 23, 2010 at 7:27 AM, Dayo Adewunmi wrote: > Hi all > > When i use PIL.Image in this script:http://dpaste.com/163588/ on an .svg > file, I get this error: http://dpaste.com/163584/ > How do i process .svg files in python? > Thanks > > Dayo > > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Hi, svg is not an image (like a bitmap), it's a vector format file, an xml file to be more precise. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Not understanding this code example. Help, please.
On Sat, Feb 13, 2010 at 7:59 AM, Kent Johnson wrote: > On Fri, Feb 12, 2010 at 11:49 PM, Eduardo Vieira > wrote: >> Hello! I was reading the latest version of Mark Pilgrim's "Dive into >> Python" and am confused with these example about the pluralization >> rules. See http://diveintopython3.org/examples/plural3.py and >> http://diveintopython3.org/generators.html#a-list-of-patterns >> Here is part of the code: >> import re >> >> def build_match_and_apply_functions(pattern, search, replace): >> def matches_rule(word): >> return re.search(pattern, word) >> def apply_rule(word): >> return re.sub(search, replace, word) >> return (matches_rule, apply_rule) >> >> patterns = \ >> ( >> ('[sxz]$', '$', 'es'), >> ('[^aeioudgkprt]h$', '$', 'es'), >> ('(qu|[^aeiou])y$', 'y$', 'ies'), >> ('$', '$', 's') >> ) >> rules = [build_match_and_apply_functions(pattern, search, replace) >> for (pattern, search, replace) in patterns] >> >> def plural(noun): >> for matches_rule, apply_rule in rules: >> if matches_rule(noun): >> return apply_rule(noun) >> >> this example works on IDLE: print plural("baby") >> My question is "baby" assigned to "word" in the inner function? It's a >> little mind bending for me... > > It is a little mind bending when you first start seeing functions used > as first-class objects. In Python functions are values that can be > passed as arguments, returned, and assigned just like any other value. > This can simplify a lot of problems. > > In this case I think the use of functions makes the code needlessly > complicated. Without build_match_and_apply_functions() and the rules > list it would look like this: > > def plural(noun): > for (pattern, search, replace) in patterns: > if re.search(pattern, noun): > return re.replace(search, replace, noun) > > which is not much longer that the original plural(), doesn't require > all the helper machinery and IMO is easier to understand. > > Kent > Thanks for the input. Yes, there are simple ways to do it. If I recall the author shows 3 or 4 different ways of doing this, each showing some of python's features. This one was to introduce the concept of closures. Cheers, Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Not understanding this code example. Help, please.
Hello! I was reading the latest version of Mark Pilgrim's "Dive into Python" and am confused with these example about the pluralization rules. See http://diveintopython3.org/examples/plural3.py and http://diveintopython3.org/generators.html#a-list-of-patterns Here is part of the code: import re def build_match_and_apply_functions(pattern, search, replace): def matches_rule(word): return re.search(pattern, word) def apply_rule(word): return re.sub(search, replace, word) return (matches_rule, apply_rule) patterns = \ ( ('[sxz]$', '$', 'es'), ('[^aeioudgkprt]h$', '$', 'es'), ('(qu|[^aeiou])y$', 'y$', 'ies'), ('$','$', 's') ) rules = [build_match_and_apply_functions(pattern, search, replace) for (pattern, search, replace) in patterns] def plural(noun): for matches_rule, apply_rule in rules: if matches_rule(noun): return apply_rule(noun) this example works on IDLE: print plural("baby") My question is "baby" assigned to "word" in the inner function? It's a little mind bending for me... Thanks, Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about time.gmtime
On Tue, Sep 29, 2009 at 8:11 AM, Eduardo Vieira wrote: > Hello, I had a problem with a script yesterday that made me puzzled. > My time zone is US Mountain Time. This script was running nice last > week, but yesterday it reported the date of today instead > So, yesterday at 5:20pm this line: > hoje = time.strftime("%a, %b %d, %Y", time.gmtime()) > > Gave me this: "Tue, Sep 29, 2009" instead of "Mon, Sep 28, 2009" > What's going on? > Minutes ago, while I was investigating this I had this output: > >>>> time.gmtime() > time.struct_time(tm_year=2009, tm_mon=9, tm_mday=29, tm_hour=14, > tm_min=48, tm_sec=49, tm_wday=1, tm_yday=272, tm_isdst=0) >>>> time.localtime() > time.struct_time(tm_year=2009, tm_mon=9, tm_mday=29, tm_hour=8, > tm_min=50, tm_sec=28, tm_wday=1, tm_yday=272, tm_isdst=1) > > I see there are 6 hours difference, but I'm sure the script ran before 6pm > Should I simply modify my code to use localtime, instead? Why did it > happen only yesterday? > > I'm using Windows XP Professional, and my clock says it's Tuesday, > Sept. 29, 2009 and 9:10 AM > > Regards, > > Eduardo > Some time ago I experienced that. And today again. I wonder if it's not related to the fact that I did some system restore operations today? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Function design
On Tue, Oct 27, 2009 at 10:14 AM, Dave Angel wrote: > > But if the file contained 0.00 as one of its items, this code would still > have the other problem I mentioned. > > DaveA > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Yes. I noticed that in another file: I had to change the line to: if '0' in row[:lastcolumn] or '0.0' in row[:lastcolumn]: I tried to express that by doing this: if '0' or '0.0' in row[:lastcolumn]: and I got very wrong results... Ouch! Don't think python is that close to English... Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Compute data usage from log
On Tue, Oct 27, 2009 at 5:33 AM, bibi midi wrote: > #!/usr/bin/env python > # -*- coding: utf-8 -*- > > ''' > Calculate internet data consumption > of service provider > Code as per help of python tutor mailing list > Created: 26-Oct-2009 > > ''' > > intro = raw_input('press enter to view your internet data consumption: ') > log_file = '/home/bboymen/mobily.data.plan' > total_consumed = 0 > for line in open(log_file): > total_consumed += int(line.split(' ')[9]) > > > total_consumed = total_consumed/100.0 > print "total data consumed is: %0.3f MB\n" % total_consumed > > > #TODO: > #1) show the list comprehension alternative method > #2) add exception handling e.g. when log_file cant be found or when key > interrupt is pressed > > # or when index[9] is not a number, etc > #3) print latest date of calculated data > > I'm working on TODO no. 3 e.g. I want to show the latest date when wvdial > generated the ppp data. This is normally the date of last line of the ppd: > > Oct 14 11:03:45 cc02695 pppd[3092]: Sent 3489538 bytes, received > 43317854 bytes. > ^ > > For the exception handling i *think* i just use the general exception method > e.g. will catch all kinds of error. I really dont know what other errors > will show up aside from the ones i listed in the TODO. Advise is > appreciated. > > > > > > On Mon, Oct 26, 2009 at 2:12 PM, Luke Paireepinart > wrote: >> >> >> On Mon, Oct 26, 2009 at 3:20 AM, Christian Witts >> wrote: >>> >>> fInput = open('/path/to/log.file', 'rb') >>> total_usage = 0 >>> for line in fInput: >>> total_usage += int(line.split(' ')[9].strip()) >>> print total_usage >> >> It's actually bad to assign a variable to the file object in this case >> (flinput = ) because Python will automatically close a file after you're >> done with it if you iterate over it directly, but if you include a reference >> it will stay open until the python program ends or you explicitly call >> flinput.close(). It doesn't matter much in this example but in general it >> is good practice to either >> 1) call foo.close() immediately after you're done using a file object, or >> 2) don't alias the file object and just over it directly so Python will >> auto-close it. >> >> Therefore a better (and simpler) way to do the above would be: >> >> total_usage = 0 >> for line in open('/path/to/log.file'): >> total_usage += int(line.split(' ')[9]) >> >> Also note you don't need to strip the input because int() coersion ignores >> whitespace anyway. And additionally you shouldn't be opening this in binary >> mode unless you're sure you want to, and I'm guessing the log file is ascii >> so there's no need for the 'rb'. (reading is default so we don't specify an >> 'r'.) >> >> >> And since I like list comprehensions a lot, I'd probably do it like this >> instead: >> >> total_usage = sum([int(line.split(' ')[9]) for line in >> open('/path/to/log.file')]) >> >> Which incidentally is even shorter, but may be less readable if you don't >> use list comprehensions often. >> >> Also, the list comprehension version is likely to be more efficient, both >> because of the use of sum rather than repeated addition (sum is implemented >> in C) and because list comprehensions in general are a tad faster than >> explicit iteration, if i recall correctly (don't hold me to that though, I >> may be wrong.) >>> >>> Of course this has no error checking and or niceties, but I will leave >>> that up to you. >> >> The same applies to my modifications. >> >> Good luck, and let us know if you need anything else! >> >> -Luke > > > > -- > Best Regards, > bibimidi > > > > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > I think you could benefit a lot from the code examples given by Dave Beazley in his presentation about generators. There are scripts that deal with just about exactly what you're looking for. Very informative material: http://www.dabeaz.com/generators/ See the presentation slides HTH Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Function design
On Tue, Oct 27, 2009 at 10:14 AM, Dave Angel wrote: > Benno Lang wrote: >> >> On Tue, Oct 27, 2009 at 8:21 AM, Dave Angel wrote: >> >>> >>> I agree with Luke's comments. But I'd like to point out an apparent bug >>> (I >>> haven't tried the code, this is just by inspection). >>> >>> You use the test >>> if '0' in row[.] >>> >>> that's not going to check for a zero value, it's going to check for a >>> zero >>> digit character somewhere in the value. So 504 would also be recognized, >>> as >>> well as 540. >>> >> >> I thought this sounded rather fishy, along the following lines: >> row is a list, so slicing it returns a list, so 'in' should compare >> the list elements (i.e. the strings contained therein) with '0'; this >> seems perfectly normal. >> >> I have checked, and thankfully the world is not upside down. It would >> only work the way you describe if row was a string, or if 'in' called >> itself recursively when it found a list. >> >> HTH, >> benno >> >> > > You are quite right, of course. I somehow missed that it was a slice, and > took it instead to be a simple subscript. > > But if the file contained 0.00 as one of its items, this code would still > have the other problem I mentioned. > > DaveA > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Thanks for your pointers, Dave. Actually the csv file have data like this: CAOCA-SD3,OCA - Sign Design Elements Vol. 3,0,0,0,0,0,0,0,0,0,0,0,0 At first I thought that the csv module would do type coercion and my original code was: if 0 in row but nothing was caught. so I change it to: if '0' in row and all was well. Especially to Luke and Alan: Yes. A function returning the number of rows with zeros seems like a sensible decision. I'm enjoying the input from this community. I first started diving into programming using AutoHotkey, for a lot of automation stuff on windows. Autohotkey is very much procedure oriented, and you can even record macros. The scripting language allows functions and several other advanced features. Sometimes I have a need and think. Let me quick do this using either Autohotkey or Python. Sometimes both. I am glad that especially being exposed to Python I am learning how to design my code for reuse, making things more flexible, etc. Thanks again. Regards, Eduardo www.expresssignproducts.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Function design
Hello, I need your help in designing a function. I have created this script to check out if certain column in some csv files has value "0": import csv def zerofound(csvfile, outputfile, lastcolumn ): """Finds columns with zero prices. Column have 0 index""" final = csv.writer(open(outputfile, 'wb'), dialect='excel') reader = csv.reader(open(csvfile, 'rb'), dialect='excel') for row in reader: if '0' in row[:lastcolumn]: final.writerow(row) if __name__ == '__main__': zerofound('pricesfrombv.csv', 'noprices_in_BV.csv', 4) zerofound('excelbv.csv', 'noprices_in_ExcelBV.csv', 6) My question is. Is it OK to create functions with no "returns"? Basically what I did resembles a subroutine, right? How could I redesign this to use "return"? Thanks for your input, Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "if clause" in list comprehensions.
On Mon, Oct 19, 2009 at 1:20 PM, Alan Gauld wrote: > > "Sander Sweers" wrote > >>> mylist = ['John', 'Canada', 25, 32, 'right'] >>> a = [item.upper() for item in mylist if type(item) == type('good')] >> >> Usually it is recommended to use hasattr() instead of type() >> hasattr(s, 'upper') > > Nope, they do completely different things > I think you might be thinking of isinstance() which can be used instead of > type(). I see you use hasattr as a means of testing for a method but that is > still different from testing type - the method names might be the same but > the functions be completely different in effect! > >>> returned this: ['JOHN', 'CANADA', 'RIGHT'] >>> I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT'] >>> So, actually the "if" acted like a filter. > > It is intended to be used as a filter. > >>> In order to use a list comprehension I created this function instead. >>> def upperfy(item) >>> try: >>> item = item.upper() >>> except AttributeError: >>> pass >>> return item > >> I would move return item under the except and remove the pass, other >> might disagree on this. > > I would :-) > Doing that would result in None being returned for each successful > conversion. The OPs code is correct (even if unnecessary) > >>> a = [upperfy(item) for item in mylist] > > a = [item.upper() if type(item) == str else item for item in mylist] > > should do it I think. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Thanks for all the guidance. I'm glad I learned I could use "else" in the list comp. after all. I thought I could, but when I tried it, I got it wrong and forgot how I did it. Yeah, I had an impression that a function was unnecessary in this case, but didn't know how to get around it. To: Emmanuel: Thanks for your remark in the case of unicode. In my code that wasn't a problem, but it's something to consider. Regards, Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] "if clause" in list comprehensions.
Hello, The other day I was making a script and decided to use a list compreehension and I found out that this code: mylist = ['John', 'Canada', 25, 32, 'right'] a = [item.upper() for item in mylist if type(item) == type('good')] returned this: ['JOHN', 'CANADA', 'RIGHT'] I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT'] So, actually the "if" acted like a filter. In order to use a list comprehension I created this function instead. def upperfy(item) try: item = item.upper() except AttributeError: pass return item a = [upperfy(item) for item in mylist] My question is? Am I solving the problem in the right way? Am I missing something? Thanks for all the help I've been getting as a newcomer. Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Troubles with lists and control flow
On Thu, Oct 8, 2009 at 3:36 PM, Luke Paireepinart wrote: > Oops, accidentally replied off-list. > > -- Forwarded message -- > From: Luke Paireepinart > Date: Thu, Oct 8, 2009 at 3:36 PM > Subject: Re: [Tutor] Troubles with lists and control flow > To: Eduardo Vieira > > > > > On Thu, Oct 8, 2009 at 2:42 PM, Eduardo Vieira > wrote: >> >> Hello I'm developing a script to compare two files, finding duplicate >> entries and matching which id of one csv file corresponds to the id of >> another csv file. >> The first version was working nice, but I wanted to postpone the >> writing to a file till the end and also make a correct csv file. The >> code is not so great and I expect to work with no more than 3000 lines >> of data in either file: >> So here is the inicial code. I hope it's not too long or complicated: > > It's a little long to be in a message body, it'd have been nice if you > posted to pastebin and chosen Python so we could have seen it with syntax > highlighting and it would guarantee it doesn't mess up your indentation, but > it's fine for now. Just keep that in mind for longer code samples. > >> >> def inbv(currentline = None): >> """writes a line of data when a date is found in BV""" >> if currentline is None: >> currentline = [] >> else: >> currentline.append(item['USER_ID']) >> currentline.append(row['CUS_NO']) >> currentline.append(item['COMPANY']) >> currentline.append(row['BVADDR1']) >> currentline.append(item['ADDRESSLINEONE']) >> currentline.append(row['BVADDRTELNO1']) >> currentline.append(item['PHONE']) >> currentline.append(row['BVCITY']) >> currentline.append(item['CITY']) >> >> return currentline > > You don't want to do it like this. > What you're saying is: > "if they didn't pass in an argument to my function, create a new list and > return an empty list. otherwise, if they did pass in a list, append an item > and return the new list." What you really want to do is "if they didn't > pass in a list, create a new one. Then append a value and return the new > list." There's a subtle difference, do you see it? You want to add an item > to the list whether or not they passed in a list in the first place, you > just want to initialize a new list first. Think about your code and how you > can change it to do that. > > At least I think that's what your issue is, I don't really understand your > code at all. > > Also: >> >> def notinbv(currentline): >> if currentline is None: >> currentline = [] > > You should go ahead and define this one the same as the previous one (with > the optional currentline parameter) unless you left it out on purpose. > > -Luke > > > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Thanks Luke. I corrected my function, but I didn't have any good result. In other words, the problem wasn't there. The problem was with my control flow... I was using a "break" under the else clause. I often get confused with control flow things... Well, the 'else' clause on a for loop is always executed when there is no "break" triggered in the loop. So, that "break" under the else was not necessary ... and was not present in my first version too... copy and paste error, I guess. Eduardo www.expresssignproducts.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Troubles with lists and control flow
Hello I'm developing a script to compare two files, finding duplicate entries and matching which id of one csv file corresponds to the id of another csv file. The first version was working nice, but I wanted to postpone the writing to a file till the end and also make a correct csv file. The code is not so great and I expect to work with no more than 3000 lines of data in either file: So here is the inicial code. I hope it's not too long or complicated: import csv import re import addrnormalize import difflib import time started = time.time() nobv = open('regnobv.csv', 'wb') yesbv = open('reginbv.csv', 'wb') bv = open(r'\\albertapdc\ESP Data\ESP Main Files\BV_Customersa.csv').read().upper() site = open(r'C:\myscripts\latestregistrants.csv').read().upper() site = re.sub(r'([0-9]{3})-([0-9]{3})-([0-9]{4})', r'\1\2\3', site) bvreader = csv.DictReader(bv.splitlines()) sitelist = csv.DictReader(site.splitlines()) def inbv(yesbv): yesbv.write(item['USER_ID'] + ',') yesbv.write(row['CUS_NO'] + ',') yesbv.write(item['COMPANY'] + ',') yesbv.write(row['BVADDR1'] + ',') yesbv.write(item['ADDRESSLINEONE']+ ',') yesbv.write(row['BVADDRTELNO1'] + ',') yesbv.write(item['PHONE'] + '\n') bvreader = list(bvreader) # or (row['NAME'] in item['COMPANY']) or (row['BVADDREMAIL'] in item['EMAIL']) for item in sitelist: for row in bvreader: if ((row['BVADDRTELNO1'] == item['PHONE'] and row['BVADDRTELNO1']) or (row['BVADDREMAIL'] == item['EMAIL'] and row['BVADDREMAIL'])): inbv(yesbv) break ## this module just makes a few string transformations to standardize both strings. Like STREET -> ST elif addrnormalize.format_address(row['BVADDR1']) == addrnormalize.format_address(item['ADDRESSLINEONE']) and row['BVADDR1'] and row['BVPROVSTATE'] == item['STATE'] and row['BVPROVSTATE']: inbv(yesbv) break ## trying some fuzzy matching here elif (difflib.SequenceMatcher(lambda x: x in " ,.-#" , row['BVADDR1'], item['ADDRESSLINEONE']).quick_ratio() > 0.87) \ and (difflib.SequenceMatcher(lambda x: x in " .-" , row['BVCITY'], item['CITY']).quick_ratio() > 0.87): inbv(yesbv) break else: nobv.write(item['USER_ID']+ ',') nobv.write(item['FIRSTNAME']+ ',') nobv.write(item['LASTNAME']+ ',') nobv.write(item['COMPANY']+ ',') nobv.write(item['EMAIL'].lower()+ ',') nobv.write(item['PHONE']+ ',') nobv.write(item['FAX']+ ',') nobv.write(item['ADDRESSLINEONE']+ ',') nobv.write(item['ADDRESSLINETWO']+ ',') nobv.write(item['CITY']+ ',') nobv.write(item['STATE']+ ',') nobv.write(item['POSTALCODE']+ ',') nobv.write(item['COUNTRY']+ ',') nobv.write('\n') nobv.close() yesbv.close() finished = time.time() print finished - started End of code --- When I try with list it does not even print the "print linha" test If I uncomment all the conditionals except the first if than I get that written to the final file: reginbv. ### How is the new function with list affecting the results? import csv import re import addrnormalize import difflib import time started = time.time() nobv = open('regnobv.csv', 'wb') bv = open(r'\\albertapdc\ESP Data\ESP Main Files\BV_Customersa.csv').read().upper() site = open(r'C:\myscripts\latestregistrants.csv').read().upper() site = re.sub(r'([0-9]{3})-([0-9]{3})-([0-9]{4})', r'\1\2\3', site) bvreader = csv.DictReader(bv.splitlines()) sitelist = csv.DictReader(site.splitlines()) list2csv = [] list_not_in_bv = [] yesbv = csv.writer(open('reginbv.csv', 'wb'), dialect="excel") nobv = csv.writer(open('regnobv.csv', 'wb'), dialect="excel") def inbv(currentline = None): """writes a line of data when a date is found in BV""" if currentline is None: currentline = [] else: currentline.append(item['USER_ID']) currentline.append(row['CUS_NO']) currentline.append(item['COMPANY']) currentline.append(row['BVADDR1']) currentline.append(item['ADDRESSLINEONE']) currentline.append(row['BVADDRTELNO1']) currentline.append(item['PHONE']) currentline.append(row['BVCITY']) currentline.append(item['CITY']) return currentline def notinbv(currentline): if currentline is None: currentline = [] else: currentline.append(item['USER_ID']) currentline.append(item['FIRSTNAME']) currentline.append(item['LASTNAME']) currentline.append(item['COMPANY']) currentline.append(item['EMAIL']) currentline.append(item['PHONE']) currentline.append(item['FAX']) currentline.append(item['ADDRESSLINEONE']) currentline.append(item['ADDRESSLINETWO']) currentline.append(item['CITY']) currentline.append(item['STATE']) currentline.append(item['POSTALCODE']) currentline.append(item['COUN
Re: [Tutor] Handling missing fields in a csv file
On Tue, Sep 29, 2009 at 3:04 PM, Dave Angel wrote: > Eduardo Vieira wrote: >> >> Hello, I have a csv file, > > a broken csv file >> >> using the ";" as a delimiter. This file >> contains addresses. My problem is that some fields are missing in some >> rows and I would like to normalize the rows for a smoother import into >> Excel, for example. >> Here is an example. This is the header: >> Company;Telephone;Address;Prov;PCode >> While most of them have this header, some data would be like this: >> Abc blaba;403-403-4545;MB ---> missing address, city, and postal code >> Acme;123-403-4545;Winnipeg;MB; >> I think a good solution would be to add delimiter to represent empty >> fields: >> Abc blaba;403-403-4545;;;MB; -->missing address and postal code >> Acme;123-403-4545;;Winnipeg;MB; >> >> Fortunately the source has province names abbreviated (2 letters). I >> could also take into account a postal code, maybe: >> Given I have 2 simple functions: >> isProvince() >> isPostalCode(): >> How I would write to the proper fields once that was returned true? >> Province has to go to row[3], and PCode to row[4] right? >> >> >> Eduardo >> >> > > On any problem of this type, the toughest part is coming up with the spec. > And sometimes you don't really know it till you've run all possible data > through a program that analyzes it. If the raw data is available to you, > I'd suggest you start there. And if it was converted to this file, and you > no longer have the raw data, then at least analyze the program that did the > faulty conversion. And if that's not possible, at least plan for your > conversion program to do enough error analysis to detect when the data does > not meet the assumptions. > > > Let me make a guess about the data, and then the program will write itself. > > (Guessing) You have a file consisting of text lines. Each line has between > two and five fields, separated by semicolon, with no semicolon appearing > inside any of the fields. None of the fields is "quoted" so parsing is > simply a matter of splitting by the semicolons. > > Each field may be blank. Multiple semicolons indicates a blank field > between them. The exhaustive list of fields and missing fields is below. > > Company Telephone Address Prov PCode (nothing missing) > > > Company Telephone Address Prov > > > Company Telephone Address > > Company Telephone > Company Telephone Prov PCode > > > Company Telephone PCode > > Company Telephone Prov > Company Telephone Address PCode > > > You have a finite list of valid Prov, so isProvince() is reliable, and you > have a reliable algorithm for PCode, so isPostalCode() is reliable. In > other words, no Address will pass isPostalCode(), no PCode will pass > isProvince(), and so on. > > So, your algorithm: Read the file, one line at a time, and split the line > into two to five fields, in a list. > If the length of the list is less than 2, report error and quit. If the > length is 2, append three blank fields. > If item2 is a province, insert a blank field just before it. if item3 is a > postalcode, insert a blank field just before it > If the (new) length of the list is 5, output the list and proceed to the > next line. Otherwise report an error and quit. > > DaveA > > Thank you for your insight Dave! I will explore your solution. Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Question about time.gmtime
Hello, I had a problem with a script yesterday that made me puzzled. My time zone is US Mountain Time. This script was running nice last week, but yesterday it reported the date of today instead So, yesterday at 5:20pm this line: hoje = time.strftime("%a, %b %d, %Y", time.gmtime()) Gave me this: "Tue, Sep 29, 2009" instead of "Mon, Sep 28, 2009" What's going on? Minutes ago, while I was investigating this I had this output: >>> time.gmtime() time.struct_time(tm_year=2009, tm_mon=9, tm_mday=29, tm_hour=14, tm_min=48, tm_sec=49, tm_wday=1, tm_yday=272, tm_isdst=0) >>> time.localtime() time.struct_time(tm_year=2009, tm_mon=9, tm_mday=29, tm_hour=8, tm_min=50, tm_sec=28, tm_wday=1, tm_yday=272, tm_isdst=1) I see there are 6 hours difference, but I'm sure the script ran before 6pm Should I simply modify my code to use localtime, instead? Why did it happen only yesterday? I'm using Windows XP Professional, and my clock says it's Tuesday, Sept. 29, 2009 and 9:10 AM Regards, Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Handling missing fields in a csv file
Hello, I have a csv file, using the ";" as a delimiter. This file contains addresses. My problem is that some fields are missing in some rows and I would like to normalize the rows for a smoother import into Excel, for example. Here is an example. This is the header: Company;Telephone;Address;Prov;PCode While most of them have this header, some data would be like this: Abc blaba;403-403-4545;MB ---> missing address, city, and postal code Acme;123-403-4545;Winnipeg;MB; I think a good solution would be to add delimiter to represent empty fields: Abc blaba;403-403-4545;;;MB; -->missing address and postal code Acme;123-403-4545;;Winnipeg;MB; Fortunately the source has province names abbreviated (2 letters). I could also take into account a postal code, maybe: Given I have 2 simple functions: isProvince() isPostalCode(): How I would write to the proper fields once that was returned true? Province has to go to row[3], and PCode to row[4] right? Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
On Sun, Sep 13, 2009 at 6:42 PM, bob gailer wrote: > Please provide a meaningful subject (other than no subject) > > > shellc...@juno.com wrote: >> >> I want to take two tuples and and print out all the elements in both >> tuples >> >> > > You probably want something different. So explain please. > Maybe he wants you to click on the weight loss link ;-)) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to print the next line in python
On Sat, Sep 12, 2009 at 10:53 PM, Lie Ryan wrote: > ranjan das wrote: >> >> Hi, >> >> I am new to python and i wrote this piece of code which is ofcourse not >> serving my purpose: >> >> Aim of the code: >> >> To read a file and look for lines which contain the string 'CL'. When >> found, print the entry of the next line (positioned directly below the >> string 'CL') continue to do this till the end of the file (since there >> are more than one occurrences of 'CL' in the file) >> >> My piece of code (which just prints lines which contain the string 'CL') >> >> f=open('somefile.txt','r') >> >> for line in f.readlines(): >> >> if 'CL' in line: >> print line >> >> >> please suggest how do i print the entry right below the string 'CL' >> >> > > Will "the next line" ever contains "CL"? And if it does, should we print the > next, next line. That is, in case of: > > abcCLdef > ghiCLjkl > mnopqrst > > should we print: > ghiCLjkl > mnopqrst > > or: > ghiCLjkl > > if the latter is the case, then you can advance the file's cursor: > > with open('myfile.txt') as f: > for line in f: > if 'CL' in line: > print next(f) > > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I like this solution, but it brings a StopIteration error in case the last line contains a 'CL' Regards, Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Making sense of "'python' is not recognized as an internal or external command...
Hello, list. Sorry, for this basic question. But why in Windows (XP) command prompt I get this message if, for example I type "python myscript.py"? But it works if I simply type myscript.py? Maybe by getting an answer for this question I could know how to make commands "grep, diff" work from any folder, and not have to type the full path for them or start in their folder...-- I have GnuWin32 utilities installed in my c:\Program Files. Thanks, Eduardo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Problems with encoding in BeautifulSoup
On Tue, Aug 18, 2009 at 5:59 AM, Kent Johnson wrote: > On Tue, Aug 18, 2009 at 12:18 AM, Mal Wanstall wrote: >> On Tue, Aug 18, 2009 at 9:00 AM, Eduardo Vieira >> wrote: > >>> Here is the Error output: >>> utf-8 >>> Traceback (most recent call last): >>> File "C:\myscripts\encondingproblem.py", line 13, in >>> print companies[:4] >>> UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in >>> position 373: ordinal not in range(128) >> >> It's caused by Python not wanting to send non-ASCII characters to your >> terminal. To override this you need to create a sitecustomize.py file >> in your /usr/lib/python/ folder and put the following in it: >> >> import sys >> sys.setdefaultencoding("utf-8") >> >> This will set the default encoding in Python to UTF8 and you should >> stop getting these parsing errors. I dealt with this recently when I >> was playing around with some international data. > > Eduardo is on Windows so his terminal encoding is probably not utf-8. > More likely it is cp437. > > Setting sys.setdefaultencoding() affects all scripts you run and will > make scripts that you write non-portable. A better solution is to > properly encode the output, for example > for company in companies[:4]: # assuming companies is a list > print company.encode('cp437') > > Kent > So, I gather that you all don't get this error, then? Anyway, running sys.getdefaultencoding() I get 'ascii' The test example from BSoup docs works differently wether I use IDLE or the cmd window in my XP. The example is: latin1word = 'Sacr\xe9 bleu!' unicodeword = unicode(latin1word, 'latin-1') print unicodeword In IDLE I get "Sacré bleu!", in the windows shell I get "Sacr\xe9 bleu!" simply trying a loop, prevents me from the error, I found out: for company in companies[:10]: print company however I can't see the accents displayed properly. This is corrected when I use this encoding: company.encode("iso-8859-1"). This way I get the right results. Thanks for pointing me to this. What remains a question is why when printing a list it throws an error and when printing the strings in the list it doesn't. Regards, Eduardo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Problems with encoding in BeautifulSoup
Hello, I have this sample script from beautiful soup, but I keep getting an error because of encoding. I have google for solutions but I don't seem to understand. Even this is dealt in Beautiful Soup's doc but I am not able to understant/apply the solution successfully. from BeautifulSoup import BeautifulSoup import urllib2 page = urllib2.urlopen('http://www.yellowpages.ca/search/si/1/Signs/QC') # if I change the url to http://www.yellowpages.ca/search/si/3/Signs/ON, it works because there's no french words... soup = BeautifulSoup(page) companies = soup('h2') print soup.originalEncoding print companies[:4] However, if I do this, I don't get errors even when there are accents: for title in companies: print title Here is the Error output: utf-8 Traceback (most recent call last): File "C:\myscripts\encondingproblem.py", line 13, in print companies[:4] UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 373: ordinal not in range(128) === Thanks in advance. Eduardo www.expresssignproducts.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] mnemonics to better learn Python
On Fri, Jul 31, 2009 at 12:27 PM, Che M wrote: > > >> To: tutor@python.org >> From: alan.ga...@btinternet.com >> Date: Fri, 31 Jul 2009 17:09:48 +0100 >> Subject: Re: [Tutor] mnemonics to better learn Python >> >> >> "Eduardo Vieira" wrote >> >> > Hello, would anybody have a good memorization technique for boolean >> > results? Like when using 'or'/'and' what it returns when both are >> > false, the last is false, etc? >> >> Hmm, I don't try to remember those, I just work it out based on >> the meaning. >> >> A and B is true only if both A and B are True >> A or B is true if either A or B is True. >> >> Thats it really, what's to remember? > > I tend to agree, but since he asked for a mnemonic... > > What Python Needs to Return a Boolean > AND: Both I demand! > OR: One or more. > > So, > > if A and B are False: > [think "Both I demand...are False") > if A or B are False: > [think "One or more...are False") > if A and B are True: > [think "Both I demand...are True") > etc. > > Che > > > > Windows Live™ SkyDrive™: Store, access, and share your photos. See how. > ___ > Tutor maillist - tu...@python.org > http://mail.python.org/mailman/listinfo/tutor > > It's not that it's so hard, but I still have to stop and think for a while... "humm, how's that?" Like in the IDLE 2 and 4 and 0 Result: 0 2 and 4 and 5 Result: 5 2 and 0 and 6 Result: 0 So, what I need to memorize is that with AND, if there's a false item, then that false is returned, otherwise the last one is returned With OR, the first one is returned if true, otherwise, the next "true" value is returned 2 or 3 or 0 Result: 2 2 or 0 or 3 Result: 2 0 or 2 or 3 Result: 2 0 or '' or 4 Result: 4 Do you see how this can demand a little more of brainwork? Eduardo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] mnemonics to better learn Python
On Thu, Jul 23, 2009 at 1:24 PM, Che M wrote: > > >> Date: Thu, 23 Jul 2009 14:05:36 +0800 >> From: ld...@gmx.net >> To: Tutor@python.org >> Subject: [Tutor] mnemonics to better learn Python >> >> Dear List, >> >> in order to memorize which Python sequences are mutable or immutable, I >> focused on the SHAPE of the brackets that are associated with each type >> of sequence. >> >> For instance, a *list* is characterised by square brackets, []. >> My mnemonic device to memorize that lists are mutable is this: "the >> brackets have sharp edges, they could be trimmed, taking their edges off". >> >> The same thing happens with *dictionaries* (which, okay, are not >> sequences). Anyway, their brackets, {}, have sharp edges, hence they are >> mutable. >> >> *Tuples*, in turn, have perfectly 'round' brackets, (), and these >> brackets obviously can't be improved upon by taking anything off them. >> Hence: tuples are immutable. >> >> That leaves us with *strings*, which are also not mutable. Here we have >> no brackets, and this particular mnemonic device breaks down. >> >> What I am interested in is finding out whether you use similar >> techniques, and if so, which ones? How, for examples, do you make sense >> of all those special characters that make regular expressions powerful? >> Do you rely on rote learning, or do you employ some other technique? >> >> I reckon that if we could come up with some tips and techniques as to >> how to uncloud the thick information fog that any beginning programmer >> has to wade through, the very first steps in learning Python could be >> made more easy. >> >> What insights can you share? > Hello, would anybody have a good memorization technique for boolean results? Like when using 'or'/'and' what it returns when both are false, the last is false, etc? I find it so hard to remember that... Eduardo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Problems understanding control flow
On Thu, Jul 30, 2009 at 5:56 PM, Eduardo Vieira wrote: > On Thu, Jul 30, 2009 at 4:49 PM, Sander Sweers wrote: >> 2009/7/30 Eduardo Vieira : >> >> With == you are testing if the 2 values are exactly the same. So 'one' >> == 'one' will return True but 'one; == 'one two' will return False. >> >> With in you test if the value is part of a another value. So using the >> same value as above 'one' in 'one' will return True but 'one' in 'one >> two' will also return True as 'one' is part of the second string. >> >> The same logic applies to lists and dicts. 'one' == ['one', 'two'] >> will return False as the the 2 values are not exactly the same but >> 'one' in ['one', 'two'] will return True. >> >>> # this does not work: >>> for row in sitelist: >>> for line in bvreaderone: >> >> If you are getting unexpected results add in print statements to see >> what is the data that you are working with. I would add the below 2 >> print statements to see what you are now actually comparing. Same >> applies to the other working example. >> : >> print 'Value row['EMAIL'] is: %s' % row['EMAIL'] >> print 'Value of line['BVADDREMAIL'] is: %s' % line['BVADDREMAIL'] >> >>> if row['EMAIL'] == line['BVADDREMAIL']: >> >> Here you are testing if the value of row['EMAIL'] is exactly the same >> as line['BVADDREMAIL']: which is not the case so the test returns >> False and the below print statement is not executed. >> >>> print line['NAME'], row['COMPANY'] >>> >>> # but this does work: >>> for row in sitelist: >>> for line in bvreaderone: >>> if row['EMAIL'] in line['BVADDREMAIL']: >> >> Here you test if the value row['E_MAIL'] is part of >> line['BVADDREMAIL']:which is True. >> >>> print line['NAME'], row['COMPANY'] >> >> Someone did a way better job writing this down some time a go but >> can't find the post online. I hope you see now what the difference is >> between the 2. > Thanks for pointing out this, Sander. Yes, a print statement revealed > the right after commas... In this case I should enable the option from > the csv module to ignore such white spaces. > > Eduardo > I meant a print statement revealed the extra space right after commas... ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Problems understanding control flow
On Thu, Jul 30, 2009 at 4:49 PM, Sander Sweers wrote: > 2009/7/30 Eduardo Vieira : > > With == you are testing if the 2 values are exactly the same. So 'one' > == 'one' will return True but 'one; == 'one two' will return False. > > With in you test if the value is part of a another value. So using the > same value as above 'one' in 'one' will return True but 'one' in 'one > two' will also return True as 'one' is part of the second string. > > The same logic applies to lists and dicts. 'one' == ['one', 'two'] > will return False as the the 2 values are not exactly the same but > 'one' in ['one', 'two'] will return True. > >> # this does not work: >> for row in sitelist: >> for line in bvreaderone: > > If you are getting unexpected results add in print statements to see > what is the data that you are working with. I would add the below 2 > print statements to see what you are now actually comparing. Same > applies to the other working example. > : > print 'Value row['EMAIL'] is: %s' % row['EMAIL'] > print 'Value of line['BVADDREMAIL'] is: %s' % line['BVADDREMAIL'] > >> if row['EMAIL'] == line['BVADDREMAIL']: > > Here you are testing if the value of row['EMAIL'] is exactly the same > as line['BVADDREMAIL']: which is not the case so the test returns > False and the below print statement is not executed. > >> print line['NAME'], row['COMPANY'] >> >> # but this does work: >> for row in sitelist: >> for line in bvreaderone: >> if row['EMAIL'] in line['BVADDREMAIL']: > > Here you test if the value row['E_MAIL'] is part of > line['BVADDREMAIL']:which is True. > >> print line['NAME'], row['COMPANY'] > > Someone did a way better job writing this down some time a go but > can't find the post online. I hope you see now what the difference is > between the 2. Thanks for pointing out this, Sander. Yes, a print statement revealed the right after commas... In this case I should enable the option from the csv module to ignore such white spaces. Eduardo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Problems understanding control flow
Hello, list. I can't understand why the print statement is not printed with the operator '==', but is printed when using 'in'. Here's the code: #=== import csv bv = """NAME,BVADDRTELNO1,BVADDREMAIL Company1, 1234567788, t...@that.com CompanyA, 1231234455, t...@this.com CompanyC, 101101, n...@this.com CompanyD, 22, o...@olde.com """ site = """Company,Email,Phone "Company3","noth...@nada.com","123456" "CompanyD","o...@olde.com","22" "Company1","t...@that.com","1234567788" """ bv = bv.upper() # This is just to make the data more homogeneous and detect duplicates more easily site = site.upper() bvreader = csv.DictReader(bv.splitlines()) sitelist = csv.DictReader(site.splitlines()) bvreaderone = list(bvreader) # this does not work: for row in sitelist: for line in bvreaderone: if row['EMAIL'] == line['BVADDREMAIL']: print line['NAME'], row['COMPANY'] # but this does work: for row in sitelist: for line in bvreaderone: if row['EMAIL'] in line['BVADDREMAIL']: print line['NAME'], row['COMPANY'] #== Regards, Eduardo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Messages not going through (testing again)
Hello, this is just a test. I have posted 2 different messages and they have never reached this list. Eduardo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] problem with csv dictreader
Hello, I'm enjoying learning python but then I come across some basic things that makes me stumped... I have 2 csv files and I want to see which ones are duplicates based on two criteria email, or telephone. The order of fields in both csv files are different. Here are a sample bogus data: import csv bv = """NAME,BVADDRTELNO1,BVADDREMAIL Company1, 1234567788, t...@that.com CompanyA, 1231234455, t...@this.com CompanyC, 101101, n...@this.com CompanyD, 22, o...@olde.com """ site = """Company,Email,Phone "Company3","noth...@nada.com","123456" "CompanyD","o...@olde.com","22" "Company1","t...@that.com","1234567788" """ bv = bv.upper() # This is just to make the data more homogeneous and detect duplicates more easily site = site.upper() bvreader = csv.DictReader(bv.splitlines(True)) sitelist = csv.DictReader(site.splitlines(True)) for row in sitelist: for line in bvreader: if row['EMAIL'] == line['BVADDREMAIL']: print line['NAME'], row['COMPANY'] #= My questions are: Why nothing is being printed? Two rows should be printed right? What would be better for the outer loop, the bigger list or the small list? The biglist (bvreader) is under 2100 lines (244Kb) and the smaller list (sitelist) can be 20 lines or less. Thanks. Eduardo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Reconstructing phrases from tagged text
Hello, I'm scratching my head into solving a problem of transforming a POS-Tagged text in a normal text. My biggest problem is that I can't get the quotes to be placed properly. I had tried a different approach but was advised in the nltk list to use this example, but it does not solve the quoting problem... #== Here's the sample code === # -*- coding: cp1252 -*- input = """TitelmanNOM riu-se V+P rir em PRP em seu ADJ seu típico ADJ típico modoNOM modo grosseiro ADJ grosseiro e CONJe respondeu V responder : SENT: " QUOTE " VocêP você prende V prender a DET a criminosos NOM criminoso e CONJe a DET a pessoas NOM pessoa más ADJ mau , VIRG, mas CONJmas eu P eu detençãoNOM detenção só ADJ só aos PRP+DET a anabatistas NOM , VIRG, quemPR quem levam V levar vidas NOM vida boasADJ bom e CONJe nunca ADV nunca fazem V fazer uso NOM uso da PRP+DET de violência NOM violência " QUOTE " . SENT. OuviV ouvir dizer V dizer que CONJSUB que o DET o servidorADJ servidor público NOM público lhe P lhe deu V dar uma DET uma boa ADJ bom respostaNOM resposta : SENT: " QUOTE " Se P se eu P eu detençãoNOM detenção a PRP a todaADJ todo a DET a gente NOM gente má ADJ mau e CONJe vocêP você prende V prender a PRP a todaADJ todo a DET a gente NOM gente boa ADJ bom , VIRG, quemPR quem ficará V ficar ? SENT? " QUOTE " +...@+ V +...@+ V –V Sabes NOM ? SENT? """ PUNCT = '!#$%)*,-.:;<=>?@/\\]^_`}~”…' LINEBREAK = '+...@+' tokens = [line.split()[0] for line in input.splitlines()]# instead output = [] for t in tokens: if t == LINEBREAK: output.append('\n') else: if t not in PUNCT: output.append(' ') output.append(t) print ''.join(output) #== It ouputs this: Titelman riu-se em seu típico modo grosseiro e respondeu: " Você prende a criminosos e a pessoas más, mas eu detenção só aos anabatistas, quem levam vidas boas e nunca fazem uso da violência ". Ouvi dizer que o servidor público lhe deu uma boa resposta: " Se eu detenção a toda a gente má e você prende a toda a gente boa, quem ficará? " – Sabes? You see, the quotes have spaces in between: My old code that didn't do the job as good was this (hairy) one: The removing of tags I had already done with "sed". myoutput = cStringIO.StringIO() f = open(r'C:\mytools\supersed\tradunew.txt') lista = [line.strip() for line in f] punct = '!#$%)*,-.:;<=>?@/\\]^_`}~”…' for i, item in enumerate(lista): if item == '"' and lista[i + 1] not in punct: myoutput.write(item) spacer = True elif '+...@+' in item: donewline = item.replace('+...@+','\n ') myoutput.write(donewline) elif item not in punct and lista[i + 1] in punct: myoutput.write(item) elif item in punct and lista[i + 1] in punct: myoutput.write(item) elif item in punct and lista[i + 1] == '"' and spacer: myoutput.write(item) spacer = False elif item not in punct and lista[i + 1] == '"' and spacer: myoutput.write(item) spacer = False elif item in '([{“': myoutput.write(item) else: myoutput.write(item + " ") newlist = myoutput.getvalue().splitlines() myoutput.close() f = open(r'C:\mytools\supersed\traducerto-k.txt', 'w') for line in newlist: f.write(line.lstrip()+'\n') f.close() So a text like this: --- Example begins No , thank...@+ # this +...@+ I inserted to mark paragraphs, because the POS-Tagger don't keep paragraph marks He said , " No , thanks . " OK ? --- Example ends --- And I want to transform into this: No, thanks. He said, "No, thanks." OK? --- End example Thanks. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Can't transform a list of tokens into a text
Hello, I have a file that was a resulted from a POS-Tagging program, after some transformations, I wanted to restore to it's normal form. So, I used sed to remove the POS-Tags and have something like this: --- Example begins No , thank...@+ # this +...@+ I inserted to mark paragraphs, because the POS-Tagger don't keep paragraph marks He said , " No , thanks . " OK ? --- Example ends --- And I want to transform into this: No, thanks. He said, "No, thanks." OK? --- End example I tried different approaches, and dealing with the quote marks is what is defeating my attempts: I had originally this code: import cStringIO ##import string myoutput = cStringIO.StringIO() f = open(r'C:\mytools\supersed\tradunew.txt') lista = [line.strip() for line in f] punct = '!#$%)*,-.:;<=>?@/\\]^_`}~”…' for i, item in enumerate(lista): if item == '"' and lista[i + 1] not in punct: myoutput.write(item) spacer = True elif '+...@+' in item: donewline = item.replace('+...@+','\n ') myoutput.write(donewline) elif item not in punct and lista[i + 1] in punct: myoutput.write(item) elif item in punct and lista[i + 1] in punct: myoutput.write(item) elif item in punct and lista[i + 1] == '"' and spacer: myoutput.write(item) spacer = False elif item not in punct and lista[i + 1] == '"' and spacer: myoutput.write(item) spacer = False elif item in '([{“': myoutput.write(item) else: myoutput.write(item + " ") newlist = myoutput.getvalue().splitlines() myoutput.close() f = open(r'C:\mytools\supersed\traducerto-k.txt', 'w') for line in newlist: f.write(line.lstrip()+'\n') f.close() #=== I tried this version to post in this forum but that gives me an error. I don't know why I don't get an error with the code above which is essentially the same: # -*- coding: cp1252 -*- result = '' lista = [ 'No', ',', 'thank...@+', 'He', 'said', ',', '"', 'no', ',', 'thanks', '.', '"', 'OK', '?', 'Hi'] punct = '!#$%)*,-.:;<=>?@/\\]^_`}~”…' for i, item in enumerate(lista): if item == '"' and lista[i + 1] not in punct: result +=item spacer = True elif '+...@+' in item: donewline = item.replace('+...@+','\n ') result += donewline elif item not in punct and lista[i + 1] in punct: result += item elif item in punct and lista[i + 1] in punct: result += item elif item in punct and lista[i + 1] == '"' and spacer: result += item spacer = False elif item not in punct and lista[i + 1] == '"' and spacer: result += item spacer = False elif item in '([{“': result += item else: result += (item + " ") print result #== The error is this: Traceback (most recent call last): File "", line 244, in run_nodebug File "C:\mytools\jointags-v4.py", line 17, in elif item not in punct and lista[i + 1] in punct: IndexError: list index out of range I'm using python 2.6.2 with PyScripter IDE I have tried a so many variations that I'm not sure what I'm doing any more I'm just trying to avoid some post-processing with sed again. Thankful, Eduardo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] My code to update database
On Fri, Jul 10, 2009 at 12:51 PM, Emile van Sebille wrote: > On 7/10/2009 11:29 AM Eduardo Vieira said... >> >> Hello! I have the code below to update a database from a csv file. I >> have tested one time and it has worked fine, but I'm a bit fearful >> that it should work right as I am updating a database and don't want >> to cause troubles into the system. >> Is this code safe for my personal use? > > Looks OK to me -- note one small change I'd make (move myconn and mycursor > to after __main__ test) , but even that's not critical. Well, I thought in the case I needed to import this module then I'd have to put it there, right? > >> the update code is in a function, but the rest of the code to connect >> and disconnect is outside the function. I thought this was a good idea >> because for each line iterated in the csv file, there is a call to the >> function to update the database with the data from the csv file. So, >> using the 'global' inside the function is ok, or maybe not? > > Looks like you don't need the global at all. Have you tried without it? > > Oh, yeah, I was getting confuse on that... probably because a another case where I did need to use the 'global' declaration ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] My code to update database
Hello! I have the code below to update a database from a csv file. I have tested one time and it has worked fine, but I'm a bit fearful that it should work right as I am updating a database and don't want to cause troubles into the system. Is this code safe for my personal use? the update code is in a function, but the rest of the code to connect and disconnect is outside the function. I thought this was a good idea because for each line iterated in the csv file, there is a call to the function to update the database with the data from the csv file. So, using the 'global' inside the function is ok, or maybe not? # --- Code starts here --- import csv import dbi import odbc myconn = odbc.odbc('DSN=MKPT01') mycursor = myconn.cursor() def inventory_update(partnumber, quantity, warehouse='00'): """Updates a given part number with the corrected quantity""" global mycursor mycursor.execute("""UPDATE INVENTORY SET ONHAND = ? WHERE CODE = ? AND WHSE = ? """, [quantity, partnumber, warehouse]) if __name__ == "__main__": csvreader = csv.reader(open('Inventory_tracker.csv', 'rb'), dialect = 'excel') for pnumber, qty in csvreader: print "%s has now %s items in stock" % (pnumber, qty) inventory_update(pnumber, qty) mycursor.close() myconn.commit() myconn.close() # --- End --- I'd appreciate your feedback. Eduardo www.expresssignproducts.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: Problems with parameter queries
On Wed, Jun 24, 2009 at 6:16 PM, Richard Lovely wrote: > (oops... forgot to reply-all) > > > -- Forwarded message -- > From: Richard Lovely > Date: 2009/6/25 > Subject: Re: [Tutor] Problems with parameter queries > To: Eduardo Vieira > > > 2009/6/24 Eduardo Vieira : >> Hello, I am accessing a Pervasive SQL data source using odbc and I'm >> having this trouble: >> >> import dbi >> import odbc >> # the first execute works >> pnumber = '09F153' >> wh = '00' >> qty = 3 >> myconn = odbc.odbc('DSN=MKPT01') >> mycursor = myconn.cursor() >> mycursor.execute(""" >> SELECT "INVENTORY"."CODE", "INVENTORY"."INV_DESCRIPTION" FROM "INVENTORY" >> WHERE "INVENTORY"."CODE" = ? AND WHSE = ? >> >> """, [pnumber, wh]) >> results = mycursor.fetchall() >> >> print results >> >> # this one below doesn't >> >> mycursor.execute("""UPDATE INVENTORY SET ONHAND = ? >> WHERE CODE = ? AND WHSE = '00' >> >> """, [pnumber, qty]) >> #mycursor.commit() >> mycursor.close() >> >> If I don't use parameter in the update code, it updates fine. Am I >> missing something? Is this a problem specific to the Pervasive SQL? >> For example, this works: >> mycursor.execute("""UPDATE INVENTORY SET ONHAND='0' >> WHERE CODE = '09F153' AND WHSE = '00' >> >> """) >> >> Thanks >> >> Eduardo >> ___ >> Tutor maillist - tu...@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > Isn't the arguement list to the non-working query back-to-front? > > -- > Richard "Roadie Rich" Lovely, part of the JNP|UK Famile > www.theJNP.com > > > Oops! My bad, I guess that was the problem. I'm going to test it soon. Thanks for spotting that! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Problems with parameter queries
Hello, I am accessing a Pervasive SQL data source using odbc and I'm having this trouble: import dbi import odbc # the first execute works pnumber = '09F153' wh = '00' qty = 3 myconn = odbc.odbc('DSN=MKPT01') mycursor = myconn.cursor() mycursor.execute(""" SELECT "INVENTORY"."CODE", "INVENTORY"."INV_DESCRIPTION" FROM "INVENTORY" WHERE "INVENTORY"."CODE" = ? AND WHSE = ? """, [pnumber, wh]) results = mycursor.fetchall() print results # this one below doesn't mycursor.execute("""UPDATE INVENTORY SET ONHAND = ? WHERE CODE = ? AND WHSE = '00' """, [pnumber, qty]) #mycursor.commit() mycursor.close() If I don't use parameter in the update code, it updates fine. Am I missing something? Is this a problem specific to the Pervasive SQL? For example, this works: mycursor.execute("""UPDATE INVENTORY SET ONHAND='0' WHERE CODE = '09F153' AND WHSE = '00' """) Thanks Eduardo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Writing a csv from a dictionary
Hello, I have a dictionary similar to this: dyc = { 'a50' : ['textfield', 50, 40], 'k77' : ['othertext', 60, 10] } I was trying to write a csv with the csv module, by doing this: import csv myfile = open('c:/myscripts/csv-test.csv', 'wb') mywriter = csv.writer(myfile, dialect='excel') for item in dyc: mywriter.write(item) myfile.close() this gives me this result: a50,"['textfield', 50, 40]" k77,"['othertext', 60, 10]" I would like this, instead: a50,"textfield", 50, 40 k77,"othertext", 60, 10 I also could manage to transform that dictionary in a list like this: [ [a50,"textfield", 50, 40], [k77,"othertext", 60, 10] Thanks in advance for your advice ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Parse Text File
On Wed, Jun 10, 2009 at 12:44 PM, Stefan Lesicnik wrote: > Hi Guys, > > I have the following text > > [08 Jun 2009] DSA-1813-1 evolution-data-server - several vulnerabilities > {CVE-2009-0547 CVE-2009-0582 CVE-2009-0587} > [etch] - evolution-data-server 1.6.3-5etch2 > [lenny] - evolution-data-server 2.22.3-1.1+lenny1 > [04 Jun 2009] DSA-1812-1 apr-util - several vulnerabilities > {CVE-2009-0023 CVE-2009-1955} > [etch] - apr-util 1.2.7+dfsg-2+etch2 > [lenny] - apr-util 1.2.12+dfsg-8+lenny2 > > ... (and a whole lot more) > > I would like to parse this so I can get it into a format I can work with. > > I don't know anything about parsers, and my brief google has made me think > im not sure I wan't to know about them quite yet! :) > (It looks very complex) > > For previous fixed string things, i would normally split each line and > address each element, but this is not the case as there could be multiple > [lenny] or even other entries. > > I would like to parse from the date to the next date and treat that all as > one element (if that makes sense) > > Does anyone have any suggestions - should I be learning a parser for doing > this? Or is there perhaps an easier way. > > Tia! > > Stefan Hello, maybe if you would show a sample on how you would like the ouput to look like it could help us give more suggestions. Regards, Eduardo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need better understanding of **kwargs
On Sat, Jun 6, 2009 at 11:10 PM, wesley chun wrote: >>> Hello, I thought I understood **kwargs until I stumbled with this >>> function: >>> >>> def changeflexion(myword, mytag, **dicty): >>> : >>> >>> but when I import the module and call: >>> a = conjugate.changeflexion('estaban', 'VLFin', conjugate.mydict) >>> I get this error: >>> TypeError: changeflexion() takes exactly 2 arguments (3 given) >>> Isn't the 3rd argument supposed to be a dictionary? >> >> No, **dicty means the function takes zero or more keyword parameters: >> > def f(a,b,**k): >> >> ... print a,b,k >> ... > > f(1,2) # no keyword parameters >> >> 1 2 {} > > f(1,2,c=3) # one keyword parameter >> >> 1 2 {'c': 3} > > f(1,2,{'c':3}) # a dictionary >> >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: f() takes exactly 2 arguments (3 given) >> >> But there is a syntax to pass keyword arguments as a dictionary: >> > f(1,2,**{'c':3}) >> >> 1 2 {'c': 3} > > > bob and mark are both correct, in their own special way. :-) what they > really meant to say is something like this: > > 1. if your entire purpose of the function is to accept a dictionary of > values and process them like you do in your function, there's no need > to make it a kwargs dict. as bob suggested, you can just remove the > "**" and keep the rest as-is. > > 2. however, if you're calling the function where there are a variable > number of keyword arguments, like mark's example: > > f('foo', 20, c=3, d=4, g='bar') > f('boo', -10, e=2.718, pi=3.14) > f('one', 'two', d=-40, e=2.718) > > ...where both the number of arguments may vary, or if the names may > vary, i.e., (c,d,g) vs. (e, pi) vs. (d, e), etc., then this is more of > a correct use case for a **kwargs variable. it's whole purpose is for > keyword arguments and not necessarily a mechanism to pass a dictionary > to a function even though you can do it. > > one exception is when you're trying to cascade a kwargs dictionary to > begin with, IOW, you're trying to continue to pass it on to yet > another function: > > def f1(, **kwargs): > : > > def f2(, **kwargs): > : > if 'bar' not in kwargs: # add another value to kwargs > kwargs['bar'] = 'foo' > rv = f1(..., **kwargs) # process by passing to f1() > > hope this helps! > -- 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 > Thanks you all. I only had time to read the replies today. Now it's more clear the meaning of **kwargs. I had also figured out that without using ** the 3rd argument (dicty) worked fine. Regards, Eduardo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Need better understanding of **kwargs
Hello, I thought I understood **kwargs until I stumbled with this function: def changeflexion(myword, mytag, **dicty): global er_verbs global ar_verbs global ir_verbs #global dicty for item in dicty: if myword in item and mytag in item[1]: if dicty[item].endswith('ar'): ending = item[0].replace(dicty[item][:-2], "") try: return dicty[item][:-2] + ar_verbs[ending] except KeyError: return item[0] elif dicty[item].endswith('er'): ending = item[0].replace(dicty[item][:-2], "") try: return dicty[item][:-2] + er_verbs[ending] except KeyError: return item[0] elif dicty[item].endswith('ir'): ending = item[0].replace(dicty[item][:-2], "") try: return dicty[item][:-2] + ir_verbs[ending] except KeyError: return item[0] else: return item[0] but when I import the module and call: a = conjugate.changeflexion('estaban', 'VLFin', conjugate.mydict) I get this error: TypeError: changeflexion() takes exactly 2 arguments (3 given) Isn't the 3rd argument supposed to be a dictionary? Thanks for all the help this list has provided me as a novice ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Parsing Bible verses
On Sat, May 23, 2009 at 3:37 AM, C or L Smith wrote: > Here is something from my toolbox of routines that might be useful for the > number ranges: > indices('-5--2') > [-5, -4, -3, -2] indices('3-4') > [3, 4] indices('3-4,10') > [3, 4, 10] > > /chris > > def indices(s,n=None): #("1-3,7")->1,2,3,7;i("1,-3--1")->1,-3,-2,-1; or > (slc,n=None)->slc.start,stop,step [for range(n)] > """Return a list of indices as defined by a MSWord print dialog-like range: > > e.g. "1,3,5-7" -> [1, 3, 5, 6, 7] > > A trailing comma will be ignored; a trailing dash will generate an > error.""" > > # ranges must be increasing: -3--4 will not generate any numbers > assert type(s) is str > r=[x.strip() for x in s.split(',')] > rv = [] > for ri in r: > if not ri: continue > if ri.find('-',1)>0: #ignore - in first position > dashat = ri.find('-',1) #start searching at position 1 > nums = ri[:dashat],ri[dashat+1:] > #one might want to use sys.maxint-1 for stop if the '-' is > encountered, the > #meaning being "from start to the end (as defined by the code > elsewhere") > #but then this should be made into an iterator rather than > generating the > #whole list > if nums[1] in ['','-']: > raise ValueError('missing number in request to indices: %s'%ri) > start, stop = [int(x.strip()) for x in nums] > for i in xrange(start, stop+1): > rv.append(i)#yield i > else: > rv.append(int(ri))#yield int(ri) > return rv > Thank you, your examples does give me some good ideas. I still want to investigate better the pyparsing solution, tho. One thing I came up with, was a way to parse and transform a list of verses, adding the book name where it was missing. This is a first step into the bigger program. Here's the code I came up with: #= import re reference = 'Luke 1:25; 2:1-5, 8; 4:23; 1 Corinthians 2:24; 3:1-10; Salm 23' def addbook(ref): parseref = re.split(r'; *', ref) for i, refe in enumerate(parseref): if refe[0].isalpha() or refe[1].isspace(): book = refe.rsplit(' ', 1) elif refe[0].isdigit() and refe[1]: vers = parseref.pop(i) parseref.insert(i, book[0] + ' ' + vers) return parseref print addbook(reference) #== This will give me this result: ['Luke 1:25', 'Luke 2:1-5, 8', 'Luke 4:23', '1 Corinthians 2:24', '1 Corinthians 3:1-10', 'Salm 23'] Now, a little farther on the topic of a Bible database. I'm not sure how I should proceed. I don't really have the db file I need, I will have to generate it somehow, from a bible software, because the version I want is for Portuguese. I have found a bible in sql, a bible in MS Access to give me some ideas on how to structure my database. But my question is do I really need a sql database for my need, since I will be only reading from it? Never adding or updating. One like sqlite. Would a pickled dictionary from Bible_reference to verse be faster? Should I work with anydbm? Thanks for your knowledge and help Eduardo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Parsing Bible verses
On Thu, May 21, 2009 at 7:03 PM, John Fouhy wrote: > 2009/5/22 Eduardo Vieira : >> I will be looking for lines like these: >> Lesson Text: Acts 5:15-20, 25; 10:12; John 3:16; Psalm 23 >> >> So, references in different chapters are separated by a semicolon. My >> main challenge would be make the program guess that 10:12 refers to >> the previous book. 15-20 means verses 15 thru 20 inclusive. I'm afraid >> that will take more than Regex and I never studied anything about >> parser tools, really. > > Well, pyparsing is one of the standard python parsing modules. It's > not that bad, really :-) > > Here's some code I knocked out: > > from pyparsing import * > > SingleVerse = Word(nums) > VerseRange = SingleVerse + '-' + SingleVerse > Verse = VerseRange | SingleVerse > Verse = Verse.setResultsName('Verse').setName('Verse') > Verses = Verse + ZeroOrMore(Suppress(',') + Verse) > Verses = Verses.setResultsName('Verses').setName('Verses') > > ChapterNum = Word(nums) > ChapterNum = ChapterNum.setResultsName('Chapter').setName('Chapter') > ChapVerses = ChapterNum + ':' + Verses > SingleChapter = Group(ChapVerses | ChapterNum) > > Chapters = SingleChapter + ZeroOrMore(Suppress(';') + SingleChapter) > Chapters = Chapters.setResultsName('Chapters').setName('Chapters') > > BookName = CaselessLiteral('Acts') | CaselessLiteral('Psalm') | > CaselessLiteral('John') > BookName = BookName.setResultsName('Book').setName('Book') > > Book = Group(BookName + Chapters) > Books = Book + ZeroOrMore(Suppress(';') + Book) > Books = Books.setResultsName('Books').setName('Books') > > All = CaselessLiteral('Lesson Text:') + Books + LineEnd() > > s = 'Lesson Text: Acts 5:15-20, 25; 10:12; John 3:16; Psalm 23' > res = All.parseString(s) > > for b in res.Books: > for c in b.Chapters: > if c.Verses: > for v in c.Verses: > print 'Book', b[0], 'Chapter', c[0], 'Verse', v > else: > print 'Book', b[0], 'Chapter', c[0] > > ## > > Hopefully you can get the idea of most of it from looking at the code. > > Suppress() means "parse this token, but don't include it in the results". > > Group() is necessary for getting access to a list of things -- you can > experiment by taking it out and seeing what you get. > > Obviously you'll need to add more names to the BookName element. > > Obviously also, there is a bit more work to be done on Verses. You > might want to look into the concept of "parse actions". A really > simple parse action might be this: > > def convertToNumber(string_, location, tokens): > """ Used in setParseAction to make numeric parsers return numbers. """ > > return [int(tokens[0])] > > SingleVerse.setParseAction(convertToNumber) > ChapterNum.setParseAction(convertToNumber) > > That should get you python integers instead of strings. You can > probably do more with parseActions to, for instance, turn something > like '15-20' into [15,16,17,18,19,20]. > > HTH! > > -- > John. > Thanks for the thorough example, I guess I really should get into this thing of parsing somehow. To W W. I guess that approach can work too. I will study both things and if I get stumped, I'll try the list again. It will take a while for me to really delve into the task, but I want to do it for a good friend of mine. Eduardo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Parsing Bible verses
Hello, I'm planning to create a script to read a certain file, find the line that contains Bible references and then use that to query a bible database in order to print the verses in another file. I will be looking for lines like these: Lesson Text: Acts 5:15-20, 25; 10:12; John 3:16; Psalm 23 So, references in different chapters are separated by a semicolon. My main challenge would be make the program guess that 10:12 refers to the previous book. 15-20 means verses 15 thru 20 inclusive. I'm afraid that will take more than Regex and I never studied anything about parser tools, really. Any suggestion how I should approach this? Eduardo www.expresssignproducts.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Using read() before closing a file
Hello, I found interesting today, as I was playing with this code in the shell: >>> arq = open('c:/myscripts/simple2.ttt', 'w') >>> len(a) 9 >>> arq.write('The length is %d' % len(a)) >>> res = arq.read() >>> print res The print doesn't print the text I had written, but some thing else I can't copy and paste to this message. But if I had closed the file and then did this: res = open('c:/myscripts/simple2.ttt').read(), it would have worked. Just thought of sharing this. Eduardo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Organizing my code, should I use functions?
On Wed, Apr 22, 2009 at 12:15 PM, bob gailer wrote: > Please use reply-all so a copy goes to the list. > Thank you very much for your help and suggestions, I've modified my code following your guidelines and looks so much better. Regards,' Eduardo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Organizing my code, should I use functions?
Hello! I’m not a programmer and am a beginner with Python, I would like suggestion about ways of tackling the task I had to do. I have bee been using the xlrd package to get data from some spreadsheets successfully. I have developed a simple report from a script that compares number of shipments recorded in 2 spreadsheets, with data from previous years and current year, respectively. Later on I was asked to include in the same report numbers from another branch of our company. So, basically all the code logic was the same, only two different files needed to be processed, and I wondered how would I save time avoiding repeating code, creating extra variables, etc. So, I simply decided to alter the code as little as possible and use the import statement. It's working this way. Sounds wise? I thought if I converted it to a function or a class would make it more flexible, but my understanding of classes are too basic yet, and am not sure if it's worth using it. I have noticed that in lot's of python code example, people make functions out of everything. I'm still too much attached to procedural, not functional programming, if I understand the terms correctly. I would appreciate any suggestions. Here is the code: ## This script creates a report of shipments ## comparing the numbers from the previous year with the current year. import xlrd # Package to read Excel files import os import glob import time import datetime import dbi import odbc thismonth = time.strftime('%B', time.gmtime()) # Get's a string with the name of the current month hoje = time.strftime("%a, %b %d, %Y", time.gmtime()) # Two excel files to process with shipping information thisyearFile = r'c:\Shipping Totals - 2009\Shipping Totals 2009 West.xls' prevyearFile = r'c:\Shipping Totals\Shipping Totals - 2008\Shipping Totals 2008 West.xls' thisDay = time.gmtime()[:3] prevyear = datetime.datetime.today() - datetime.timedelta(days=365) aYearAgo = prevyear.timetuple()[:3] ## --- Code to find the right cell with today's shipments book = xlrd.open_workbook(thisyearFile) # Opens excel file dayexcel = xlrd.xldate.xldate_from_date_tuple(thisDay, book.datemode) #Puts the date in the Excel format, like 3991.0 sh = book.sheet_by_name(thismonth) # The sheet which has the name of the month: April, May, June, etc. firstCol = sh.col_values(0) # Retrieves the first column tperday = firstCol.index('TOTAL Per Day') # Finds the cell 'Total Per Day' shipindex = tperday + 1 # The next cell after 'TOTAL Per Day', which contains the info about shipments # Looks for the column whose header is today's date for cols in range(sh.ncols): for valores in sh.col_values(cols): if valores == dayexcel: # If it finds the column with today's date todaysList = sh.col_values(cols) totals = sh.row_values(shipindex, end_colx=cols + 1) # sum up to the current date break # Crosses rows with column to find the right cell with the shipments of today shippedToday = todaysList[shipindex] totalShipments = sum([a for a in totals if type(a) == type(2.0)]) # Sums all shipments # Check previous year's shipments processing the file with last year's data booktwo = xlrd.open_workbook(prevyearFile) dayexcel = xlrd.xldate.xldate_from_date_tuple(aYearAgo, book.datemode) sh = booktwo.sheet_by_name(thismonth) firstCol = sh.col_values(0) tperday = firstCol.index('TOTAL Per Day') shipindex = tperday + 1 for cols in range(sh.ncols): for valores in sh.col_values(cols): if valores == dayexcel: lastyearsList = sh.col_values(cols) totals = sh.row_values(shipindex, end_colx=cols + 1) # sum up to the current date break shippedLastYear = lastyearsList[shipindex] OldTotalShipments = sum([a for a in totals if type(a) == type(2.0)]) # Imports the information from the Eastern division. See code on the bottom import bizreportereast as bz report = """ = Shipments Alberta Warehouse = - Shipments today: %d - Shipments this month: %d - Shipments this day, last year: %d - Shipments this month, last year: %d = Shipments Ontario Warehouse = - Shipments today: %d - Shipments this month: %d - Shipments this day, last year: %d - Shipments this month, last year: %d """ % (shippedToday, totalShipments, shippedLastYear, OldTotalShipments, bz.shippedToday, bz.totalShipments, bz.shippedLastYear, bz.OldTotalShipments) print report logfile = open('c:/myscripts/logbizreport.log', 'a') Code found in bizreportereast.py import xlrd import os import glob import time import datetime ## --- Code to find the right cell with today's shipments thismonth = time.strftime('%B', time.gmtime()) hoje = time.strftime("%a, %b %d, %Y", time.gmtime()) thisyearFile = r'c:\MS Excel\Shipping Totals\Shipping Totals - 2009\Shipping Totals 2009 East.xls' prevyearFile = r'c:\MS Excel\Shipping Totals\Shipping Totals - 2008\Shipping Totals 2008 East.xls' thisDay = time.gmtime()[
[Tutor] Can't run this script while I'm logged off of Windows XP
Hello, I'm making a script that daily grabs some information and email it to some of my coworkers. It runs all the other parts while I'm logged off, but this part doesn't. I need to be logged on for it to work. Also, when I'm logged on to my Windows XP I just can't make it send. It only sits in my mailbox. I have to manually press "send" to get it sent. here is the code that won't work: import win32com.client try: s = win32com.client.Dispatch("Mapi.Session") s.Logon("Default") Msg = s.Outbox.Messages.Add("Daily Activity Report", report) testaddresses = [ 'te...@expresssignproducts.com', ##'1...@expresssignproducts.com', ##'2...@expresssignproducts.com', ##'3...@expresssignproducts.com', ] for address in testaddresses: Msg.Recipients.Add(address) Msg.Send() s.DeliverNow() s.Logoff() except: logfile.write("Couldn't write email") #=== So, I'm coming to a conclusion that it is not possible to send emails while logged off. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Evaluating Swahili Part of Speech Tagging. How can I write a Python script for that?
2009/3/24 Emad Nawfal (عماد نوفل) : > Evaluating Swahili Part of Speech Tagging. How can I write a Python script > for that? > # The information provided herein about Swahili may not be accurate > # it is just intended to illustrate the problem > Hello, Mr. Emad! Have you checked the NLTK (Natural Language Toolkit - http://www.nltk.org ) a Python package for Linguistics applications? Maybe they have something already implemented. I actually liked a lot their tutorials about python and using pythons for Linguistics. Very good explanations. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trouble parsing email from Outlook
On Fri, Mar 20, 2009 at 2:29 PM, Eduardo Vieira wrote: > On Fri, Mar 20, 2009 at 9:04 AM, Tim Golden wrote: >> Eduardo Vieira wrote: >>> >>> Thank you very much, Tim for the thorough explanation. Much more than >>> I could expect. It will be specially useful for me a newbie python >>> amateur programmer. I will try your guidance as soon as possible >>> today, and see my progress. >> >> That's ok; might be worth posting back to the list to say >> whether it worked or not. All the posts go into the archive >> so people looking in the future for the same kind of solution >> might be interested to know if my suggestion worked or >> whether there were any other obstacles. >> >> TJG >> > Thanks again. I tried the code, trying to reformat the spaces and came > up with this code: http://paste.lisp.org/display/77353 > I'm not sure if I indented correctly, and the result it gave me was: > Searching Archive Folders > Searching Mailbox - Eduardo Silva > > I don't understand the part "for folder, folders, items in cdo_walk > (info_store.RootFolder):" > RootFolder is IPM_SUBTREE if I check the Name value > I worked! sorry, I had to just align "raise x_found" with the "for" statement, thank you very much! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Trouble parsing email from Outlook
Hello, list! I hope it's not too much out of place to ask this question in the Tutor list. I'm trying to process some information from email messages that goes in a folder called: "SysAdmin". I could reproduce the recipe from Python Programming on Win32 sucessfully to read the subject line of the inbox, but not from a different folder: So far my code is this: import win32com.client ses = win32com.client.Dispatch("Mapi.Session") o = win32com.client.Dispatch("Outlook.Application") ses.Logon("Default") print ses.Inbox.Messages.Item(1).Subject How can I check stuff from the folder "SysAdmin", then? I get lost with the references from CDO, MAPI with Visual Basic code (I don't understad VB) I get from Microsoft and other sites. Thanks for any pointer. Eduardo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to connect to an email server?
Tim wrote: > > > SMTP has to be enabled specifically on the Exchange Server: > it usually uses its own built-in protocols. It looks > as though your Exchange isn't running it. Either switch it > on (or ask your admins to do so) or look at using MAPI > or CDO instead. > > TJG > ___ > Tutor maillist - tu...@python.org > http://mail.python.org/mailman/listinfo/tutor > I guess I'll use MAPI, CDO, as these have worked before. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to connect to an email server?
Hello, I'm fairly new to programming and Python and am trying to explore Python's email libraries. But I am having trouble making a connection with an email server, I guess. I'm running Windows XP, in a server environment. I have administrator privileges to my machine (not the server machine) to install, delete programs, for example. My email program (Outlook 2007) says that Exchange Server is albertapdc.express.local I would like to send emails using smtp in a script, but when I do these lines, I get an error: import smtplib server = smtplib.SMTP('localhost') # if I replace 'localhost' with 'albertapdc.express.local' I get the same. Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\smtplib.py", line 244, in __init__ (code, msg) = self.connect(host, port) File "C:\Python25\lib\smtplib.py", line 310, in connect raise socket.error, msg error: (10061, 'Connection refused') The same error 'Connection refused' I get trying IMAP: import imaplib se = imaplib.IMAP4('albertapdc.express.local') Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\imaplib.py", line 163, in __init__ self.open(host, port) File "C:\Python25\lib\imaplib.py", line 230, in open self.sock.connect((host, port)) File "", line 1, in connect error: (10061, 'Connection refused') What should I do? And how can I know I can use smtp or IMAP? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] What does OP stand for?
Hello, I'm new to this list, and am enjoying it. I just wonder what "OP" stands for, as I have seen quite a few mentions in the python lists Thanks Edu ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Modifying a QIF
Hello, this weekend I had fun using Python for text processing. I needed to change a qif converted from a ofx, using the tool MT2OFX (http://www.xs4all.nl/~csmale/mt2ofx/en/index.htm) I wanted to change transactions like these: D11/14/2008 MCHEQUE 102 17590807;Cheque or Preauth. Debit T-500.00 N102 ^ Into this: D11/14/2008 MCHEQUE 102 17590807;Cheque or Preauth. Debit T-500.00 N102 PLorne Koehn LHousing:Rent == That is, insert those given Payee and Category if the transaction was a cheque of 500.00 I came up with these two versions and would like to know which should be more efficient or practical. Could you point improvements? VERSION ONE: f = open('cibc.QIF', 'r').readlines() for line in range(len(f)): if f[line] == 'T-500.00\n': f[line+1] += 'PLorne Koehn\nLHousing:Rent\n' new = open('cibc.QIF', 'w') new.writelines(f) VERSION TWO: f = open('cibc.QIF', 'rw') g = open('newresult.qif', 'w') flag = 0 for line in f: if line == 'T-500.00\n': flag = 1 elif line.startswith('N') and flag: flag = 0 line += 'PLorne Koehn\nLHousing:Rent\n' g.write(line) f.close() #== One thing like about version 1 is that I can overwrite the same file, and don't need to create another one. I haven't figured out how to do the same with the second version and overcoming the IOError. Thanks for your attention Edu ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Very basic question about lists
Wesley wrote: On Mon, Dec 22, 2008 at 1:19 PM, wesley chun wrote: > > in addition, i think (and i may be wrong about this) that he really > wanted to do: > > if 'arr' in list1 or 'bell' in list1... > Thanks for all the replies. Yes that was actually what I meant. My mistake too was that I gave you all a wrong example to explain my problem, sorry. The following example will explain better: list1 = ['ar', 'fir', 'wo'] list2 = ['ber', 'gar', 'gt'] list3 = ['hu', 'mo', 'ko', 'tr'] list4 = ['q', 'wer', 'duh'] whole = [list1, list2, list3, list4] for item in whole: if 'ar' or 'ko' in item: print item So, the unexpected result was that I got all lists printed, when I expected only list1 and list3. Now, I don't know if I still understand the explanation given by spir -- I'll reread more carefully--, but I know that the code to get what I expect is this instead: for item in whole: for word in item: if word == 'ar' or word == 'ko': print item I see I have to do a loop inside a loop and that this the right expression if word == 'ar' or word == 'ko': but this is not: if word == 'ar' or 'ko': ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Very basic question about lists
Hello, I'm trying to teach my self programming with python and there are some basic things that stumps me: Given this code: ### list1 = ['arr', 'bre', 'grau', 'lower', 'tudo'] for item in list1: if 'arr' in item: print list1 ### The output is (as expected): ['arr', 'bre', 'grau', 'lower', 'tudo'] If I change my condition to: if 'arr' or 'bell' in item: or to this: if 'arr' or 'grau' in item: I get this result: ['arr', 'bre', 'grau', 'lower', 'tudo'] ['arr', 'bre', 'grau', 'lower', 'tudo'] ['arr', 'bre', 'grau', 'lower', 'tudo'] ['arr', 'bre', 'grau', 'lower', 'tudo'] ['arr', 'bre', 'grau', 'lower', 'tudo'] Why this? I guess I'm not grasping the use of AND and OR Thanks, Eduardo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looping, and Win32com.client
Thank you, now it worked! I made these changes to my code: for ficheiro in os.listdir(folder): file = os.path.join(folder, ficheiro) #added this if ficheiro.endswith('.xls'): wb = xl.Workbooks.Open(file, 2) # changed this On Fri, Dec 19, 2008 at 8:57 AM, Tim Golden wrote: > Eduardo Vieira wrote: >> >> Hello, this is my first post in this list and I'm not a programmer, >> but am enjoying learning python. >> I'm trying to make a script to add worksheets to excel files: >> I managed to implement this code: >> >> import os >> folder = 'C:\\Personal\\oldxlsformat\\' >> from win32com.client import Dispatch >> xl = Dispatch('Excel.Application') >> xl.Application.AskToUpdateLinks = "False" >> for ficheiro in os.listdir(folder): > > > os.listdir returns a list of files relative to > the directory in question. (Try it at the > interpreter and see). Excel requires, pretty > much, a list of absolute filenames. So try > using something like os.path.join (folder, ficheiro) > when opening in Excel. > > TJG > ___ > 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] Looping, and Win32com.client
Hello, this is my first post in this list and I'm not a programmer, but am enjoying learning python. I'm trying to make a script to add worksheets to excel files: I managed to implement this code: import os folder = 'C:\\Personal\\oldxlsformat\\' from win32com.client import Dispatch xl = Dispatch('Excel.Application') xl.Application.AskToUpdateLinks = "False" for ficheiro in os.listdir(folder): if ficheiro.endswith('.xls'): wb = xl.Workbooks.Open(ficheiro, 2) wb.Worksheets.Add().Name = "BVTest" wb.Close(SaveChanges = 1) xl.Quit() but then I get this error: Traceback (most recent call last): File "C:\Personal\exceltests4.py", line 8, in wb = xl.Workbooks.Open(ficheiro, 2) File ">", line 8, in Open com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Office Excel', u"'AVERY GRAPHICS INK JET.xls' could not be found. Check the spelling of the file name, and verify that the file location is correct.\n\nIf you are trying to open the file from your list of most recently used files, make sure that the file has not been renamed, moved, or deleted.", u'C:\\Program Files\\Microsoft Office\\Office12\\1033\\XLMAIN11.CHM', 0, -2146827284), None) The files I have as a test are these: C:\Personal\oldxlsformat\AVERY GRAPHICS INK JET.xls C:\Personal\oldxlsformat\CUTTING MATS & RULERS.xls C:\Personal\oldxlsformat\Oracal - Ontario Stocking Order.xls C:\Personal\oldxlsformat\ORACAL 8100-8500.xls ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor