[Tutor] FW: wierd replace problem
Hello, Strip ('"'') does not work. Still this message : SyntaxError: EOL while scanning string literal So I think I go for the suggestion of Bob en develop a programm which deletes all the ' and " by scanning it character by character. Roelof > >> From: st...@pearwood.info >> To: tutor@python.org >> Date: Tue, 14 Sep 2010 09:39:29 +1000 >> Subject: Re: [Tutor] wierd replace problem >> >> On Tue, 14 Sep 2010 09:08:24 am Joel Goldstick wrote: >>> On Mon, Sep 13, 2010 at 6:41 PM, Steven D'Aprano >> wrote: On Tue, 14 Sep 2010 04:18:36 am Joel Goldstick wrote: > How about using str.split() to put words in a list, then run > strip() over each word with the required characters to be removed > ('`") Doesn't work. strip() only removes characters at the beginning and end of the word, not in the middle: >>> >>> Exactly, you first split the words into a list of words, then strip >>> each word >> >> Of course, if you don't want to remove ALL punctuation marks, but only >> those at the beginning and end of words, then strip() is a reasonable >> approach. But if the aim is to strip out all punctuation, no matter >> where, then it can't work. >> >> Since the aim is to count words, a better approach might be a hybrid -- >> remove all punctuation marks like commas, fullstops, etc. no matter >> where they appear, keep internal apostrophes so that words like "can't" >> are different from "cant", but remove external ones. Although that >> loses information in the case of (e.g.) dialect speech: >> >> "'e said 'e were going to kill the lady, Mister Holmes!" >> cried the lad excitedly. >> >> You probably want to count the word as 'e rather than just e. >> >> And hyphenation is tricky to. A lone hyphen - like these - should be >> deleted. But double-dashes--like these--are word separators, so need to >> be replaced by a space. Otherwise, single hyphens should be kept. If a >> word begins or ends with a hyphen, it should be be joined up with the >> previous or next word. But then it gets more complicated, because you >> don't know whether to keep the hyphen after joining or not. >> >> E.g. if the line ends with: >> >> blah blah blah blah some- >> thing blah blah blah. >> >> should the joined up word become the compound word "some-thing" or the >> regular word "something"? In general, there's no way to be sure, >> although you can make a good guess by looking it up in a dictionary and >> assuming that regular words should be preferred to compound words. But >> that will fail if the word has changed over time, such as "cooperate", >> which until very recently used to be written "co-operate", and before >> that as "coöperate". >> >> >> >> -- >> Steven D'Aprano >> ___ >> Tutor maillist - Tutor@python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
On 14-09-10 09:28, Roelof Wobben wrote: Hello, Strip ('"'') does not work. Still this message : SyntaxError: EOL while scanning string literal Review it again, see how many quotes you are using. For example, this won't work either: >>> s = 'foo'bar' You need to escape the quotes with a backslash, like: >>> s = 'foo\'bar' >>> print s foo'bar Cheers, Timo So I think I go for the suggestion of Bob en develop a programm which deletes all the ' and " by scanning it character by character. Roelof From: st...@pearwood.info To: tutor@python.org Date: Tue, 14 Sep 2010 09:39:29 +1000 Subject: Re: [Tutor] wierd replace problem On Tue, 14 Sep 2010 09:08:24 am Joel Goldstick wrote: On Mon, Sep 13, 2010 at 6:41 PM, Steven D'Aprano wrote: On Tue, 14 Sep 2010 04:18:36 am Joel Goldstick wrote: How about using str.split() to put words in a list, then run strip() over each word with the required characters to be removed ('`") Doesn't work. strip() only removes characters at the beginning and end of the word, not in the middle: Exactly, you first split the words into a list of words, then strip each word Of course, if you don't want to remove ALL punctuation marks, but only those at the beginning and end of words, then strip() is a reasonable approach. But if the aim is to strip out all punctuation, no matter where, then it can't work. Since the aim is to count words, a better approach might be a hybrid -- remove all punctuation marks like commas, fullstops, etc. no matter where they appear, keep internal apostrophes so that words like "can't" are different from "cant", but remove external ones. Although that loses information in the case of (e.g.) dialect speech: "'e said 'e were going to kill the lady, Mister Holmes!" cried the lad excitedly. You probably want to count the word as 'e rather than just e. And hyphenation is tricky to. A lone hyphen - like these - should be deleted. But double-dashes--like these--are word separators, so need to be replaced by a space. Otherwise, single hyphens should be kept. If a word begins or ends with a hyphen, it should be be joined up with the previous or next word. But then it gets more complicated, because you don't know whether to keep the hyphen after joining or not. E.g. if the line ends with: blah blah blah blah some- thing blah blah blah. should the joined up word become the compound word "some-thing" or the regular word "something"? In general, there's no way to be sure, although you can make a good guess by looking it up in a dictionary and assuming that regular words should be preferred to compound words. But that will fail if the word has changed over time, such as "cooperate", which until very recently used to be written "co-operate", and before that as "coöperate". -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
> Date: Tue, 14 Sep 2010 09:32:38 +0200 > From: timomli...@gmail.com > To: tutor@python.org > Subject: Re: [Tutor] FW: wierd replace problem > > On 14-09-10 09:28, Roelof Wobben wrote: >> >> >> Hello, >> >> Strip ('"'') does not work. >> Still this message : SyntaxError: EOL while scanning string literal >> > Review it again, see how many quotes you are using. > > For example, this won't work either: s = 'foo'bar' > > You need to escape the quotes with a backslash, like: s = 'foo\'bar' print s > foo'bar > > > Cheers, > Timo Hello Timo, I understand what you mean but we're talking about a text-file which will be read in a string. So I can't escape the quotes. As far as I know I can't control how Python is reading a text-file with quotes. Roelof > >> So I think I go for the suggestion of Bob en develop a programm which >> deletes all the ' and " by scanning it character by character. >> >> Roelof >> >> >> >>> >>> From: st...@pearwood.info To: tutor@python.org Date: Tue, 14 Sep 2010 09:39:29 +1000 Subject: Re: [Tutor] wierd replace problem On Tue, 14 Sep 2010 09:08:24 am Joel Goldstick wrote: > On Mon, Sep 13, 2010 at 6:41 PM, Steven D'Aprano > wrote: >> On Tue, 14 Sep 2010 04:18:36 am Joel Goldstick wrote: >> >>> How about using str.split() to put words in a list, then run >>> strip() over each word with the required characters to be removed >>> ('`") >>> >> Doesn't work. strip() only removes characters at the beginning and >> end of the word, not in the middle: >> > Exactly, you first split the words into a list of words, then strip > each word > Of course, if you don't want to remove ALL punctuation marks, but only those at the beginning and end of words, then strip() is a reasonable approach. But if the aim is to strip out all punctuation, no matter where, then it can't work. Since the aim is to count words, a better approach might be a hybrid -- remove all punctuation marks like commas, fullstops, etc. no matter where they appear, keep internal apostrophes so that words like "can't" are different from "cant", but remove external ones. Although that loses information in the case of (e.g.) dialect speech: "'e said 'e were going to kill the lady, Mister Holmes!" cried the lad excitedly. You probably want to count the word as 'e rather than just e. And hyphenation is tricky to. A lone hyphen - like these - should be deleted. But double-dashes--like these--are word separators, so need to be replaced by a space. Otherwise, single hyphens should be kept. If a word begins or ends with a hyphen, it should be be joined up with the previous or next word. But then it gets more complicated, because you don't know whether to keep the hyphen after joining or not. E.g. if the line ends with: blah blah blah blah some- thing blah blah blah. should the joined up word become the compound word "some-thing" or the regular word "something"? In general, there's no way to be sure, although you can make a good guess by looking it up in a dictionary and assuming that regular words should be preferred to compound words. But that will fail if the word has changed over time, such as "cooperate", which until very recently used to be written "co-operate", and before that as "coöperate". -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor >> ___ >> Tutor maillist - Tutor@python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to numerically sort strings that start with numbers?
Pete O'Connell wrote: > theList = ["21 trewuuioi","3zxc","134445"] > print sorted(theList) > > Hi, the result of the sorted list above doesn't print in the order I > want. Is there a straight forward way of getting python to print > ['3zxc','21 trewuuioi','134445'] > rather than ['134445', '21 trewuuioi', '3zxc']? You have to write a function that extracts the number and use it as the key argument for sorted() or list.sort(): >>> import re >>> def extract_number(s): ... m = re.compile(r"-?\d+").match(s) ... if m is not None: ... return int(m.group()) ... >>> theList = ["21 trewuuioi","3zxc","134445"] >>> sorted(theList, key=extract_number) ['3zxc', '21 trewuuioi', '134445'] Have a look as str.isdigit() if you want to write such a function without regular expressions. Peter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
On 14 September 2010 08:38, Roelof Wobben wrote: > > I understand what you mean but we're talking about a text-file which will > be read in a string. > So I can't escape the quotes. As far as I know I can't control how Python > is reading a text-file with quotes. > > Putting a value into a string via Python source code is not the same as putting a value into a string by reading a file. When you read a file it's implicit that whatever's in the file (including quotes) will end up in the string. There's no ambiguity so no need to worry about escaping. In Python source code however, quotes have meaning implied by context, so you have to encode/write strings differently *in source* in order to disambiguate your intention. In other words, when Python encounters a first quote in source code, it interprets this as the start of a string. When it encounters the next quote of the same type, it interprets this as the end of the string, and so on. If you therefore want to put a quote of the same type you're using to delineate a string inside of that same string, you need to "escape" the quote, e.g. tell Python to not interpret the quote as it normally would and to rather take it literally and as part of the current string value being read. This you do by putting a backslash (e.g. \ ) before it. Of course, the same problem happens when you want to put backslash itself in a string, so the backslash itself also need to be escaped in order to be put inside a string in Python. HTH Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
On Tue, Sep 14, 2010 at 5:28 PM, Roelof Wobben wrote: > Strip ('"'') does not work. > Still this message : SyntaxError: EOL while scanning string literal > > So I think I go for the suggestion of Bob en develop a programm which deletes > all the ' and " by scanning it character by character. I seriously don't understand why you're having so much trouble with this and why this thread has gotten as long as it has :/ Look here: $ python Python 2.6.5 (r265:79063, Jun 13 2010, 14:03:16) [GCC 4.4.4 (CRUX)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> s = "foo\"bar'" >>> s 'foo"bar\'' >>> s.replace("\"", "").replace("'", "") 'foobar' >>> Surely you can use the same approach ? cheers James -- -- James Mills -- -- "Problems are solved by method" ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
On 14 September 2010 11:09, James Mills wrote: > $ python > Python 2.6.5 (r265:79063, Jun 13 2010, 14:03:16) > [GCC 4.4.4 (CRUX)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> s = "foo\"bar'" > >>> s > 'foo"bar\'' > I'd like to point something out here. Typing "s" as James showed here at the prompt outputs a version of the string that Python will understand if fed again, consequently it's encoded to do the same escaping of characters as you would have to do if you put that expression into your python source yourself. If however you entered: print s ... then Python would've print the value of s as it really is, withou any escape characters or anything else, e.g.: >>> print s foo"bar' So, even though you see a \' in the output posted by James above, the \ that was output by Python isn't actually part of the string (e.g. it's not really there as such), it was only output that way by Python to disambiguate the value of the string. So, at the risk of belaboring this point to death, if you do: s = '\'\'\'' then the contents of the string s in memory is ''' The string does not contain the slashes. The slashes are only there to help you make Python understand that the quotes must not be interpreted as the end of the string, but rather as part of the string. You could get the exact same result by doing: s = "'''" Here there's no ambiguity and consequently no need for slashes since the string is delineated by double quotes and not single quotes. Hope that helps. Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
On 13/09/2010 20.21, Roelof Wobben wrote: ... The problem as stated in the book is : 3.Write a program called alice_words.py that creates a text file named alice_words.txt containing an alphabetical listing of all the words found in alice_in_wonderland.txt together with the number of times each word occurs. The first 10 lines of your output file should look something like this: Word Count === a 631 a-piece 1 abide 1 able 1 about 94 above 3 absence 1 absurd 2How many times does the word, alice, occur in the book? The text can be found here : http://openbookproject.net/thinkcs/python/english2e/resources/ch10/alice_in_wonderland.txt So I open the file. Read the first rule. This is no problem for me. Then I want to remove some characters like ' , " when the word in the text begins with these characters. And there is the problem. The ' and " can't be removed with replace. Not true. Your problem with replace() and strip() lies in the way you gave them the characters to remove, not in the file nor in the functions themselves. For example, you said: Strip ('"'') does not work. Still this message : SyntaxError: EOL while scanning string literal Let's take a look into your argument: ( parens to start the argument ' first quote begins a string literal; " first character to remove, you want to delete all double quotes. OK. ' ... what is this? Is it the end of the string, or is it another character to remove? ' This solves the doubt: '' means that the first string is over, and another has started. OK. (maybe not what you expected...) ) OUCH! The argument has finished, but the string has not! So, End Of Line has been reached while your argument string was still open. Error. The correct syntax (and you know where to look to read it!) should be: MyText.strip('"\'') The backslash tells Python that you want to include the following single quote in your string without terminating it, then the next single quote gives a proper end to the string itself. Earlier, you said: I have tried that but then I see this message : File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 8 letter2 = letter.strip('`") ^ SyntaxError: EOL while scanning string literal Change it to (''`"") do not help either. Sure: as some pointed out before, those arguments are NOT proper string literals, as the first one doesn't start and end with the SAME quoting character, while the second is made from two empty strings with a floating backquote ` between them. If you want to strip (or replace) the three quoting characters ' " and ` , you should enclose them in a properly formatted string literal, that is one that starts and ends with the same quoting character and that, if must contain the same character, has it quoted by backslash: .strip("'\"`") Am i now clear what the problem is Im facing. Roelof I hope so. After having cut away all unwanted characters, you still have to face the main request from your tutorial, and THE question:(Sorry, Hamlet!) How many times does the word "alice" occur in the book? I would guess... none! Keep up your "fishing" Francesco Nessun virus nel messaggio in uscita. Controllato da AVG - www.avg.com Versione: 9.0.851 / Database dei virus: 271.1.1/3132 - Data di rilascio: 09/13/10 08:35:00 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
Oke, Can this also be the same problem. In the text is this : 'tis is represent as "'this And this part is represent as part. Roelof > Date: Tue, 14 Sep 2010 11:41:28 +0100 > From: wpr...@gmail.com > To: tutor@python.org > Subject: Re: [Tutor] FW: wierd replace problem > > > > On 14 September 2010 11:09, James Mills >> > wrote: > $ python > Python 2.6.5 (r265:79063, Jun 13 2010, 14:03:16) > [GCC 4.4.4 (CRUX)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. s = "foo\"bar'" s > 'foo"bar\'' > > I'd like to point something out here. Typing "s" as James showed here > at the prompt outputs a version of the string that Python will > understand if fed again, consequently it's encoded to do the same > escaping of characters as you would have to do if you put that > expression into your python source yourself. If however you entered: > > print s > > ... then Python would've print the value of s as it really is, withou > any escape characters or anything else, e.g.: > print s > foo"bar' > > So, even though you see a \' in the output posted by James above, the \ > that was output by Python isn't actually part of the string (e.g. it's > not really there as such), it was only output that way by Python to > disambiguate the value of the string. > > So, at the risk of belaboring this point to death, if you do: > > s = '\'\'\'' > > then the contents of the string s in memory is ''' > > The string does not contain the slashes. The slashes are only there to > help you make Python understand that the quotes must not be interpreted > as the end of the string, but rather as part of the string. You could > get the exact same result by doing: > > s = "'''" > > Here there's no ambiguity and consequently no need for slashes since > the string is delineated by double quotes and not single quotes. > > Hope that helps. > > Walter > > ___ Tutor maillist - > Tutor@python.org To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] If/elif/else when a list is empty
On Tue, 14 Sep 2010 02:08:43 pm Vince Spicer wrote: > Hey Tyler you can simplify this with a onliner. > > rg1, rg2, rg3 = rgenre + ["NA"]*(3-len(rgenre[:3])) There's no real need to calculate the exact length that you want: rg1, rg2, rg3 = (rgenre + ["NA"]*3)[:3] For small numbers of items -- and three is pretty small -- that will be plenty efficient enough. If you had thousands of items, perhaps not, but for three, it's not worth the effort to try to be more clever. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A Plea for Sensible Quoting
On Tue, 14 Sep 2010 09:42:15 pm Michael Powe wrote: > Just a plea to remember to take the time to `C-k' or `dd' or whatever > is required to get that extraneous material out of the mail. A > little formatting goes a long way. Seconded, thirded, fourthed and fifthed. For those using a GUI email reader, select the unnecessary text with your mouse or keyboard, and press the backspace or delete key. See, not hard, was it? I find myself deleting more and more emails unread. After paging down through two or three pages of quoting, without seeing a single new word, I just give up and press delete. There is absolutely no reason to include the entire history of the discussion every single time you post. Take a little bit of care in your responses please -- you're learning to be a programmer, you're supposed to be smarter and more capable than the average Myspacer or Facebooker. Thank you. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
On Tue, 14 Sep 2010 05:38:18 pm Roelof Wobben wrote: > >> Strip ('"'') does not work. > >> Still this message : SyntaxError: EOL while scanning string > >> literal [...] > I understand what you mean but we're talking about a text-file which > will be read in a string. So I can't escape the quotes. As far as I > know I can't control how Python is reading a text-file with quotes. The text file has nothing to do with this. The text file is fine. The error is in the strings that YOU type, not the text file. Strings must have MATCHING quotation marks: This is okay: "abcd" So is this: 'abcd' But this is not: "abcd' You need to *look carefully* at strings you type and make sure that the start and end quotes match. Likewise you can't insert the SAME quotation mark in a string unless you escape it first: This is okay: "'Hello,' he said." So is this: '"Goodbye," she replied.' But this is not: 'He said "I can't see you."' But this is okay: 'He said "I can\'t see you."' -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] wierd replace problem
On Tue, 14 Sep 2010 03:28:46 am Alan Gauld wrote: > "Roelof Wobben" wrote > > > Now I want to get rid of the \\ so I do this : test2 = test.replace > > ('\\', '') > > And I get at the python prompt this answer : 'het is een wonder > > TIS' So that's right. > > OK,. Thats replacing a double slash in the data Er, surely not... I think you've confused backslashes and forward slashes. Or something. '\\' is a single backslash, not a double, because the first backslash is the escape character. A double backslash can be written ''. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] A Plea for Sensible Quoting
Hello, I read this list in a linux console using mutt. I dunno, maybe I'm the only idiot left still using a console mail client. I write my emails and email replies in emacs, too, which may make me even weirder. Few elements make a mail harder to read than 130 lines of nested quoting, into which has been inserted 3 or 5 lines of comment. Mutt does a good job of identifying the quote nesting and highlighting the quoted material; and I can use the `T' command to remove the quoting. But sometimes, "context" in the sense of what was being replied to is useful. When a thread reponse is quoting 3 other respondents plus the OP, "context" turns into "what everybody is saying," which is more like standing in a crowded train terminal, where everybody is shouting, than having a quiet, private conversation among 4 people. Then, I have to page down four screens to find the 5 lines of new comment, and try to figure out what portion of that three-level-nested dialog that preceeds it was the trigger for the response. Just a plea to remember to take the time to `C-k' or `dd' or whatever is required to get that extraneous material out of the mail. A little formatting goes a long way. Thanks. mp -- Michael Powemich...@trollope.orgNaugatuck CT USA Fun experiments: Get a can of shaving cream, throw it in a freezer for about a week. Then take it out, peel the metal off and put it where you want... bedroom, car, etc. As it thaws, it expands an unbelievable amount. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to numerically sort strings that start with numbers?
On Tue, 14 Sep 2010 11:11:33 am Adam Bark wrote: > On 14/09/10 01:11, Pete O'Connell wrote: > > theList = ["21 trewuuioi","3zxc","134445"] > > print sorted(theList) > > > > Hi, the result of the sorted list above doesn't print in the order > > I want. Is there a straight forward way of getting python to print > > ['3zxc','21 trewuuioi','134445'] > > rather than ['134445', '21 trewuuioi', '3zxc']? > > > > Any help would be greatly appreciated > > Pete > > print sorted(theList)[::-1] That's a very inefficient way of doing it. First it makes a copy of the list, then it sorts it, then it makes *another* copy in reverse. A better way is: sorted(theList, reverse=True) -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to numerically sort strings that start with numbers?
> > ['3zxc','21 trewuuioi','134445'] > > > rather than ['134445', '21 trewuuioi', '3zxc']? > > > > > > Any help would be greatly appreciated > > > Pete > > There seem to be two different ways of understand the OP sort order. > The way I took it, 3zxc comes first because the number is 3 which is smaller than 21 which is smaller than 134445. It happened to be a coincidence that the list reversed was in that same order. So, if I am right about the definition of how to sort, the method I would use is to strip each string of anything beyond its leading digits, save that as a key, use the string as the value. Then sort by key -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] If/elif/else when a list is empty
On Tue, 14 Sep 2010 01:58:07 pm aenea...@priest.com wrote: > if len(rgenre)>0: > if len(rgenre)>2: > rg1=rgenre[0] > rg2=rgenre[1] > rg3=rgenre[2] > elif len(rgenre)==2: > rg1=rgenre[0] > rg2=rgenre[1] > rg3="NA" > elif len(rgenre)==1: > rg1=rgenre[0] > rg2="NA" > rg3="NA" >else len(rgenre)<1: # I was hoping this would take care of the > "there is no genre information" scenario but it doesn't > rg1=rg2=rg3="NA" The above will give a SyntaxError, because you can't have a condition immediately after an else. This is a neater way to write the above: n = len(rgenre) if n == 0: rg1 = rg2 = rg3 = "NA" elif n == 1: rg1 = rgenre[0] rg2 = rg3 = "NA" elif n == 2: rg1, rg2 = rgenre[0:2] rg3 = "NA" else: rg1, rg2, rg3 = rgenre[:3] which in turn can be shortened to the slightly cryptic one-liner: rg1, rg2, rg3 = (rgenre + ["NA"]*3)[:3] as already discussed earlier. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list index out of range
My humble guess: (sure, the full traceback would help A LOT!) On 09/09/2010 23.52, Todd Ballard wrote: y=[daily_solar_radiation["MJ"][0]] for i in xrange(0,275): y=[daily_solar_radiation["MJ"]][i]+y[i-1] # <--THIS y[i-1] is out of bounds when i=0 !!! Hope that helps Francesco Nessun virus nel messaggio in uscita. Controllato da AVG - www.avg.com Versione: 9.0.851 / Database dei virus: 271.1.1/3132 - Data di rilascio: 09/13/10 08:35:00 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
> From: st...@pearwood.info > To: tutor@python.org > Date: Tue, 14 Sep 2010 21:30:01 +1000 > Subject: Re: [Tutor] FW: wierd replace problem > > On Tue, 14 Sep 2010 05:38:18 pm Roelof Wobben wrote: > Strip ('"'') does not work. Still this message : SyntaxError: EOL while scanning string literal > [...] >> I understand what you mean but we're talking about a text-file which >> will be read in a string. So I can't escape the quotes. As far as I >> know I can't control how Python is reading a text-file with quotes. > > The text file has nothing to do with this. The text file is fine. The > error is in the strings that YOU type, not the text file. > > Strings must have MATCHING quotation marks: > > This is okay: "abcd" > So is this: 'abcd' > > But this is not: "abcd' > > You need to *look carefully* at strings you type and make sure that the > start and end quotes match. Likewise you can't insert the SAME > quotation mark in a string unless you escape it first: > > This is okay: "'Hello,' he said." > So is this: '"Goodbye," she replied.' > > But this is not: 'He said "I can't see you."' > > But this is okay: 'He said "I can\'t see you."' > > > > > -- > Steven D'Aprano > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Oke, I see the problem. When I have this sentence : `'Tis so,' said the Duchess: `and the moral of that is--"Oh, 'tis love, 'tis love, that makes the world go round!"' And I do string.strip() the output will be : `'This and that one does not fit your explanation. So I have to strip everything before I strip it. Roelof ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
On Tue, Sep 14, 2010 at 10:29 AM, Roelof Wobben wrote: I offer my solution. I didn't bother to make every word lower case, and I think that would improve the result Please offer critique, improvements Some explaination: line 5 -- I read the complete text into full_text, while first replacing -- with a space line 7 -- I split the full text string into words lines 8 - 15 -- Word by word I strip all sorts of characters that aren't in words from the front and back of each 'word' lines 11 - 14 -- this is EAFP -- try to add one to the bin with that word, if no such bin, make it and give it 1 lines 16, 17 -- since dicts don't sort, sort on the keys then loop thru the keys to print out the key (word) and the count > > 1 #! /usr/bin/env python 2 3 word_count = {} 4 file = open ('alice_in_wonderland.txt', 'r') 5 full_text = file.read().replace('--',' ') 6 7 full_text_words = full_text.split() 8 for words in full_text_words: 9 stripped_words = words.strip(".,!?'`\"- ();:") 10 ##print stripped_words 11 try: 12 word_count[stripped_words] += 1 13 except KeyError: 14 word_count[stripped_words] = 1 15 16 ordered_keys = word_count.keys() 17 ordered_keys.sort() 18 ##print ordered_keys 19 print "All the words and their frequency in 'alice in wonderland'" 20 for k in ordered_keys: 21 print k, word_count[k] 22 -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
> From: rwob...@hotmail.com > To: joel.goldst...@gmail.com > Subject: RE: [Tutor] FW: wierd replace problem > Date: Tue, 14 Sep 2010 15:43:42 + > > > > > >> Date: Tue, 14 Sep 2010 11:28:10 -0400 >> From: joel.goldst...@gmail.com >> To: tutor@python.org >> Subject: Re: [Tutor] FW: wierd replace problem >> >> >> >> On Tue, Sep 14, 2010 at 10:29 AM, Roelof Wobben >>> wrote: >> >> I offer my solution. I didn't bother to make every word lower case, >> and I think that would improve the result >> >> Please offer critique, improvements >> >> >> Some explaination: >> >> line 5 -- I read the complete text into full_text, while first >> replacing -- with a space >> line 7 -- I split the full text string into words >> lines 8 - 15 -- Word by word I strip all sorts of characters that >> aren't in words from the front and back of each 'word' >> lines 11 - 14 -- this is EAFP -- try to add one to the bin with that >> word, if no such bin, make it and give it 1 >> lines 16, 17 -- since dicts don't sort, sort on the keys then loop thru >> the keys to print out the key (word) and the count >> >> >> 1 #! /usr/bin/env python >> 2 >> 3 word_count = {} >> 4 file = open ('alice_in_wonderland.txt', 'r') >> 5 full_text = file.read().replace('--',' ') >> 6 >> 7 full_text_words = full_text.split() >> 8 for words in full_text_words: >> 9 stripped_words = words.strip(".,!?'`\"- ();:") >> 10 ##print stripped_words >> 11 try: >> 12 word_count[stripped_words] += 1 >> 13 except KeyError: >> 14 word_count[stripped_words] = 1 >> 15 >> 16 ordered_keys = word_count.keys() >> 17 ordered_keys.sort() >> 18 ##print ordered_keys >> 19 print "All the words and their frequency in 'alice in wonderland'" >> 20 for k in ordered_keys: >> 21 print k, word_count[k] >> 22 >> -- >> Joel Goldstick >> >> >> ___ Tutor maillist - >> Tutor@python.org To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > Hello Joel, Your solution works. Im getting grazy. I tried it two days with strip and get a eof error message and now no messages. Roelof ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
On 14/09/2010 16.29, Roelof Wobben wrote: ... Oke, I see the problem. When I have this sentence : `'Tis so,' said the Duchess: `and the moral of that is--"Oh, 'tis love, 'tis love, that makes the world go round!"' And I do string.strip() the output will be : `'This and that one does not fit your explanation. So I have to strip everything before I strip it. After some trial and error with the interpreter, I found this: st = """`'Tis so,' said the Duchess: `and the moral of that is--"Oh, 'tis love, 'tis love, that makes the world go round!"'""" # notice the starting and ending triple quotes, just to avoid all the backslashes and the ambiguities with quoting characters ;-) wordlist = [thisone.strip("""'",!` :-""") for thisone in st.replace('"', " ").replace("-"," ").split()] I don't know if you read the chapter regarding "list comprehensions" in your tutorial, but this is one of those. First of all, I replace all double quotes " and dashes - with spaces: st.replace('"', " ").replace("-"," ") then I use split() to divide the long string in a list of almost-words. At the end, with the for clause in the list comprehension, I strip all leading and trailing non-letters (again, I enclose them in a triple-quoted string) from each of the elements of the list. In the end, I have wordlist: ['Tis', 'so', 'said', 'the', 'Duchess', 'and', 'the', 'moral', 'of', 'that', 'is', 'Oh', 'tis', 'love', 'tis', 'love', 'that', 'makes', 'the', 'world', 'go', 'round', ''] What about this? Was it confusing? Roelof Francesco Nessun virus nel messaggio in uscita. Controllato da AVG - www.avg.com Versione: 9.0.851 / Database dei virus: 271.1.1/3132 - Data di rilascio: 09/13/10 08:35:00 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
Date: Tue, 14 Sep 2010 17:45:35 +0200 From: f...@libero.it To: tutor@python.org Subject: Re: [Tutor] FW: wierd replace problem On 14/09/2010 16.29, Roelof Wobben wrote: >... > Oke, > > I see the problem. > > When I have this sentence : `'Tis so,' said the Duchess: `and the moral of > that is--"Oh, > 'tis love, 'tis love, that makes the world go round!"' > > And I do string.strip() the output will be : > > `'This and that one does not fit your explanation. > So I have to strip everything before I strip it. After some trial and error with the interpreter, I found this: st = """`'Tis so,' said the Duchess: `and the moral of that is--"Oh, 'tis love, 'tis love, that makes the world go round!"'""" # notice the starting and ending triple quotes, just to avoid all the backslashes and the ambiguities with quoting characters ;-) wordlist = [thisone.strip("""'",!` :-""") for thisone in st.replace('"', " ").replace("-"," ").split()] I don't know if you read the chapter regarding "list comprehensions" in your tutorial, but this is one of those. First of all, I replace all double quotes " and dashes - with spaces: st.replace('"', " ").replace("-"," ") then I use split() to divide the long string in a list of almost-words. At the end, with the for clause in the list comprehension, I strip all leading and trailing non-letters (again, I enclose them in a triple-quoted string) from each of the elements of the list. In the end, I have wordlist: ['Tis', 'so', 'said', 'the', 'Duchess', 'and', 'the', 'moral', 'of', 'that', 'is', 'Oh', 'tis', 'love', 'tis', 'love', 'that', 'makes', 'the', 'world', 'go', 'round', ''] What about this? Was it confusing? > > Roelof Francesco hello Franceso, It was not confusing when I read your explanation. Still im grazy wht with you and Joel the strip works and with me I get errors. But how can I use the triple quotes when reading a textf-file ? Roelof ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] re.findall parentheses problem
Hi all, I have a regex that matches dates in various formats. I've tested the regex in a reliable testbed, and it seems to match what I want (dates in formats like "1 Jan 2010" and "January 1, 2010" and also "January 2008"). It's just that using re.findall with it is giving me weird output. I'm using Python 2.6.5 here, and I've put in line breaks for clarity's sake: >>> import re >>> date_regex = re.compile(r"([0-3]?[0-9])?((\s*)|(\t*))((Jan\.?u?a?r?y?)|(Feb\.?r?u?a?r?y?)|(Mar\.?c?h?)|(Apr\.?i?l?)|(May)|(Jun[e.]?)|(Jul[y.]?)|(Aug\.?u?s?t?)|(Sep[t.]?\.?e?m?b?e?r?)|(Oct\.?o?b?e?r?)|(Nov\.?e?m?b?e?r?)|(Dec\.?e?m?b?e?r?))((\s*)|(\t*))(2?0?[0-3]?[0-9]\,?)?((\s*)|(\t*))(2?0?[01][0-9])") >>> test_output = re.findall(date_regex, 'January 1, 2008') >>> print test_output [('', '', '', '', 'January', 'January', '', '', '', '', '', '', '', '', '', '', '', ' ', ' ', '', '20', '', '', '', '08')] >>> test_output = re.findall(date_regex, 'January 1, 2008') >>> print test_output [('', '', '', '', 'January', 'January', '', '', '', '', '', '', '', '', '', '', '', ' ', ' ', '', '1,', ' ', ' ', '', '2008')] >>> test_output = re.findall(date_regex, "The date was January 1, 2008. But it was not January 2, 2008.") >>> print test_output [('', ' ', ' ', '', 'January', 'January', '', '', '', '', '', '', '', '', '', '', '', ' ', ' ', '', '1,', ' ', ' ', '', '2008'), ('', ' ', ' ', '', 'January', 'January', '', '', '', '', '', '', '', '', '', '', '', ' ', ' ', '', '2,', ' ', ' ', '', '2008')] A friend says: " I think that the problem is that every time that you have a parenthesis you get an output. Maybe there is a way to suppress this." My friend's explanation speaks to the empties, but maybe not to the two Januaries. Either way, what I want is for re.finall, or some other re method that perhaps I haven't properly explored, to return the matches and just the matches. I've read the documentation, googled various permutations etc, and I can't figure it out. Any help much appreciated. Thanks, Mike ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
On 14-09-10 17:44, Roelof Wobben wrote: 9 stripped_words = words.strip(".,!?'`\"- ();:") Hello Joel, Your solution works. Im getting grazy. I tried it two days with strip and get a eof error message and now no messages. Look at the backslash! It doesn't strip the backslash in the string, but it escapes the double quote following it. I don't know how people can explain it any better. You *do* see that this doesn't work, right? >>> s = "foo"bar" So you can't do this either: >>> word.strip(",.!";:") You need to escape the quote between the quotes: >>> word.strip(".,!\";:") Timo Roelof ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
On Tue, Sep 14, 2010 at 12:35 PM, Roelof Wobben wrote: > > > > > But how can I use the triple quotes when reading a textf-file ? > Roelof > The triple quotes let you put quotes inside them... for instance if you want to check for single and double quotes, and ) you can do this: """'")""" its hard to make out.. so with double spacing (you can't do this.. just to illustrate:): """ ' " ) """ > > > -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] re.findall parentheses problem
> I have a regex that matches dates in various formats. I've tested the regex > in a reliable testbed, and it seems to match what I want (dates in formats > like "1 Jan 2010" and "January 1, 2010" and also "January 2008"). It's just > that using re.findall with it is giving me weird output. I'm using Python > 2.6.5 here, and I've put in line breaks for clarity's sake: > > >>> import re > > >>> date_regex = > >>> re.compile(r"([0-3]?[0-9])?((\s*)|(\t*))((Jan\.?u?a?r?y?)|(Feb\.?r?u?a?r?y?)|(Mar\.?c?h?)|(Apr\.?i?l?)|(May)|(Jun[e.]?)|(Jul[y.]?)|(Aug\.?u?s?t?)|(Sep[t.]?\.?e?m?b?e?r?)|(Oct\.?o?b?e?r?)|(Nov\.?e?m?b?e?r?)|(Dec\.?e?m?b?e?r?))((\s*)|(\t*))(2?0?[0-3]?[0-9]\,?)?((\s*)|(\t*))(2?0?[01][0-9])") This will also match '1 Janry 2010'. Not sure if it should? two examples > >>> test_output = re.findall(date_regex, "The date was January 1, 2008. But > >>> it was not January 2, 2008.") > > >>> print test_output > [('', ' ', ' ', '', 'January', 'January', '', '', '', '', '', '', '', '', '', > '', '', ' ', ' ', '', '1,', ' ', ' ', '', '2008'), ('', ' ', ' ', '', > 'January', 'January', '', '', '', '', '', '', '', '', '', '', '', ' ', ' ', > '', '2,', ' ', ' ', '', '2008')] > > A friend says: " I think that the problem is that every time that you have a > parenthesis you get an output. Maybe there is a way to suppress this." > > My friend's explanation speaks to the empties, but maybe not to the two > Januaries. Either way, what I want is for re.finall, or some other re method > that perhaps I haven't properly explored, to return the matches and just the > matches. > > I've read the documentation, googled various permutations etc, and I can't > figure it out. Any help much appreciated. The docs say: " If one or more groups are present in the pattern, return a list of groups". So your friend is right. In fact, your last example shows exactly this: it shows a list of two tuples. The tuples contain individual group matches, the two list elements are your two date matches. You could solve this by grouping the entire regex (so r"(([0-3 [0-9]))" ; I would even use a named group), and then picking out the first tuple element of each list element: [(' January 1, 2008', '', ' ', ' ', '', 'January', 'January', '', '', '', '', '', '', '', '', '', '', '', ' ', ' ', '', '1,', ' ', ' ', '', '2008'), (' January 2, 2008', '', ' ', ' ', '', 'January', 'January', '', '', '', '', '', '', '', '', '', '', '', ' ', ' ', '', '2,', ' ', ' ', '', '2008')] Hth, Evert ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] re.findall parentheses problem
Hi Evert, Thank you. I should have figured "groups" were the paren groups. I see it clearly now. And your solution will work for the larger thing I'm trying to do --- thanks. And yes: I know this matches some non-date-like dates, but the data is such that it should work out ok. Thanks again, Mike > This will also match '1 Janry 2010'. > Not sure if it should? > > > > A friend says: " I think that the problem is that every time that you > have a parenthesis you get an output. Maybe there is a way to suppress > this." > > > The docs say: " If one or more groups are present in the pattern, return a > list of groups". So your friend is right. > > In fact, your last example shows exactly this: it shows a list of two > tuples. The tuples contain individual group matches, the two list elements > are your two date matches. > You could solve this by grouping the entire regex (so r"(([0-3 > [0-9]))" ; I would even use a named group), and then picking out the first > tuple element of each list element: > [(' January 1, 2008', '', ' ', ' ', '', 'January', 'January', '', '', '', > '', '', '', '', '', '', '', '', ' ', ' ', '', '1,', ' ', ' ', '', '2008'), > (' January 2, 2008', '', ' ', ' ', '', 'January', 'January', '', '', '', '', > '', '', '', '', '', '', '', ' ', ' ', '', '2,', ' ', ' ', '', '2008')] > > > Hth, > > Evert > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A Plea for Sensible Quoting
On Tue, Sep 14, 2010, Michael Powe wrote: >Hello, > >I read this list in a linux console using mutt. I dunno, maybe I'm the >only idiot left still using a console mail client. I write my emails >and email replies in emacs, too, which may make me even weirder. Mutt in xterms here with vi (I've never been able to get my fingers retrained for emacs after almost 30 years of vi :-). Agreed on the quoting. Interspersing new information between quoted sections is great, but quoting an entire message only to add ``ditto'' at the end is idiotic. Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 Democracy extends the sphere of individual freedom, Democracy attaches all possible value to each man, while socialism makes each man a mere agent, a mere number. Democracy and socialism have nothing in common but one word: equality. But notice the difference: while democracy seeks equality in liberty, socialism seeks equality in restraint and servitude. Alexis de Tocqueville == 1848 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
- Original message - > Look at the backslash! It doesn't strip the backslash in the string, but > it escapes the double quote following it. > > I don't know how people can explain it any better. Maybe the link below makes it clear what backslash really does. http://pythonconquerstheuniverse.wordpress.com/2008/06/04/gotcha-%e2%80%94-backslashes-are-escape-characters/ Greets sander ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
> From: rwob...@hotmail.com > To: sander.swe...@gmail.com > Subject: RE: [Tutor] FW: wierd replace problem > Date: Tue, 14 Sep 2010 17:40:28 + > > > > > >> From: sander.swe...@gmail.com >> To: tutor@python.org >> Date: Tue, 14 Sep 2010 19:28:28 +0200 >> Subject: Re: [Tutor] FW: wierd replace problem >> >> >> - Original message - >>> Look at the backslash! It doesn't strip the backslash in the string, but >>> it escapes the double quote following it. >>> >>> I don't know how people can explain it any better. >> >> Maybe the link below makes it clear what backslash really does. >> >> http://pythonconquerstheuniverse.wordpress.com/2008/06/04/gotcha-%e2%80%94-backslashes-are-escape-characters/ >> >> Greets >> sander >> ___ >> Tutor maillist - Tutor@python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > Oke, I get it. When I want to delete a " I have to use a backslash. For me case closed. Everyone thanks for the patience and explanations. Roelof ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
On 14/09/2010 18.35, Roelof Wobben wrote: ... It was not confusing when I read your explanation. Still im grazy wht with you and Joel the strip works and with me I get errors. But how can I use the triple quotes when reading a textf-file ? Very easy: YOU DON'T NEED TO USE ANY QUOTES. All the quoting stuff is ONLY needed for literals, that is for those strings you directly write in a program. For example: MyString = """ these are my favourite quoting characters: "'` """ # here you need to avoid ambiguities, because quoting chars are also used to start and end the string. You could obtain EXACTLY the same string with backslash-quoting: YourString = ' these are my favourite quoting characters: "\'` ' # here I had to quote the single-quote char HerString = " these are my favourite quoting characters: \"'` " # and here the double quote had to be quoted by backslash But when you DON'T write the string yourself, you don't need any quoting: ThisString = MyString + YourString + HerString # no quoting required ThatString = file.read() # again, NO QUOTING REQUIRED. Roelof Francesco Nessun virus nel messaggio in uscita. Controllato da AVG - www.avg.com Versione: 9.0.851 / Database dei virus: 271.1.1/3132 - Data di rilascio: 09/13/10 08:35:00 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] re.findall parentheses problem
On Tue, Sep 14, 2010 at 01:09:21PM -0400, Michael Scharf wrote: > Thank you. I should have figured "groups" were the paren groups. I see it > clearly now. And your solution will work for the larger thing I'm trying to > do --- thanks. > And yes: I know this matches some non-date-like dates, but the data is such > that it should work out ok. Hello, I second the advice to use named groups. This option makes it sooo much easier to retrieve your captures; especially, if you have nested groups. No more working out if the capture you want is in group 1 or group 3. Just matcher.group('January'). Thanks. mp -- Michael Powemich...@trollope.orgNaugatuck CT USA "We had pierced the veneer of outside things. We had `suffered, starved, and triumphed, groveled down yet grasped at glory, grown bigger in the bigness of the whole.' We had seen God in his splendors, heard the text that Nature renders. We had reached the naked soul of man." -- Sir Ernest Shackleton, pgpCawppq4rj0.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
Roelof, On 14 September 2010 17:35, Roelof Wobben wrote: > But how can I use the triple quotes when reading a textf-file ? > To repeat what I said before, obviously not clearly enough: All the quoting stuff, escaping stuff, all of that ONLY APPLIES TO STRINGS/DATA INSIDE OF YOUR PYTHON CODE. It does NOT APPLY TO DATA INSIDE OF FILES! Why not to files? Because there's no ambiguity in data inside a file. It's understood that everything in a file is just data. By contrast, in Python code, quote characters have *meaning*. Specifically they indicate the start and end of string literals. So when they themselves are part of teh string you have to write them specially to indicate their meaning, either as closing the string, or as part of the string data. In a file by contrast, every character is presumed to be just a piece of data, and so quotes have no special inherent meaning to Python, so they just represent themselves and always just form part of the data being read from the file. Do you understand what I'm saying? If you have any doubt please respond so we can try to get this cleared up -- Unless and until you realise there's a difference between data in a file and string literals in your python source code you're not going to undertand what you're doing here. Regards, Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
> Date: Tue, 14 Sep 2010 21:05:06 +0100 > Subject: Re: [Tutor] FW: wierd replace problem > From: wpr...@gmail.com > To: rwob...@hotmail.com > CC: tutor@python.org > > Roelof, > > On 14 September 2010 17:35, Roelof Wobben >> wrote: > But how can I use the triple quotes when reading a textf-file ? > > To repeat what I said before, obviously not clearly enough: All the > quoting stuff, escaping stuff, all of that ONLY APPLIES TO STRINGS/DATA > INSIDE OF YOUR PYTHON CODE. It does NOT APPLY TO DATA INSIDE OF > FILES! Why not to files? Because there's no ambiguity in data inside > a file. It's understood that everything in a file is just data. By > contrast, in Python code, quote characters have *meaning*. > Specifically they indicate the start and end of string literals. So > when they themselves are part of teh string you have to write them > specially to indicate their meaning, either as closing the string, or > as part of the string data. > > In a file by contrast, every character is presumed to be just a piece > of data, and so quotes have no special inherent meaning to Python, so > they just represent themselves and always just form part of the data > being read from the file. Do you understand what I'm saying? If you > have any doubt please respond so we can try to get this cleared up -- > Unless and until you realise there's a difference between data in a > file and string literals in your python source code you're not going to > undertand what you're doing here. > > Regards, > > Walter I understand it but I try to understand why in a file there is this 'word python makes a "'word. I know that a file is just data but I thought that if that data is read in a string I could work with the quoting stuff. But im very wrong here. Roelof ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] how best to implement paginated data in CLI
I'm using python 3.1 with py-postgresql (located at http://python.projects.postgresql.org/ I need to work through how best to paginate larger sql result sets. my SELECT statement returns a list, I can get its len() to find out that X records were returned What I want to do is print the first N records and include a Previous/Next Choice at the bottom. I know I'll be making some use of the start and stop optional parameters in the for loop that processes the list. I think that I'll need variables for the page size (#of records per screen) and a start position for where to begin in the list. I want to make this a function so that its reusable code Here is a first draft of the idea: (untested) def paginate_stuff(list,start) pagesize = 10 for row in list[start:start+pagesize] print(row["column"]) print ("\n") message = "" prompt = "" if not start == 0: message = message + "Previous" prompt = prompt + "P" if not start ==0 and not start+pagesize >= len(list): message = message + " or " prompt = prompt + " or " if not start+pagesize >= len(list): message = message + "Next" prompt = prompt + "N" print((message+"\n") choice = input(prompt+"? ") if choice == "n' or "N": paginate_stuff(list,start + pagesize) if choice == "p" or "P": paginate_stuff(list,start - pagesize) return I'm not certain at this writing of the proper syntax of the if statement conditions, I will look that up to be sure the syntax is right. What I want to ask about is the logic flow, does this make sense? Am I thinking about the problem the right way? Is there a better way to pull this off? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
On 14 September 2010 21:10, Roelof Wobben wrote: > I understand it but I try to understand why in a file there is this 'word > python makes a "'word. > Python doesn't change what it reads from the file. However, depending on how you ask Python to tell you what it's read (or what the contents of a string variable is), it might display it quoted, and/or include escape charaters, or not as the case may be. If what you've read from the file contains quotes, then obviously you need to be careful to not mistake Python's quoting of the value of a string as being *part* of that string. Neither must you mistake the escape character (if applicable) from being actually part of the string. For example, consider the following exchange in the Python shell (please try all of this yourself and experiment): >>> s = 'blah' >>> s 'blah' >>> print s blah >>> I assign the value of 'blah' to the string s. So far simple enough. Obviosuly the quotes used int the assignment of the string does not form part of the string itself. Their utility is only to delineate to Python the start of the string, and the end of the string. In the next line I ask Python to evaluate the expression s, which it duly reporst as 'blah'. Again, it's using normal Python convention to format the data as a string, because that's what s is, a string object. But the quotes are formatting, they're not really part of the string. In the next line I ask Python to *print *s. Now, the true content of s is printed as it is, and hence you can see that the quotes are not part of the string. Now consider the following exchange in the Python shell where I open a file and write some text to it to prove this point: >>> f = open('test.txt', 'w+') >>> f.write('blah') >>> f.close() >>> import os >>> os.system('notepad test.txt') The last line above opens the text file test.txt in Notepad so you can see the contents. As you can see, no quotes or anything else. Now, while open, suppose we put a single quote in the file, so it reads: 'blah ...and suppose we then save it and exit notepad so you're back in the Python shell. Then we do: >>> f=open('test.txt','r+') >>> s=f.read() >>> f.close() >>> s "'blah" Now I've read the contents of the file back into a string variable s, and asked Python to evaluate (output) this string object. Notice, Python is now formatting the string with *doube* quotes (previously it defaulted to single quotes) to avoid having to escape the single quote that forms part of the string. If Python had used single quotes instead, then there would've been an ambiguity with the single quote that's part of the string and so it would've had to escape that too. So consequently it formats the string with double quotes, which is valid Python syntax and avoids the backslash. (Stating the obvious, strings can be quoted with double or single quotes.) As before, the double quotes, as with the single quotes earlier, are not part of the string. They are merely formatting since Python is being asked to display a string and hence it must indicate the start and end of the string with suitable quote characters. Now, as before do: >>> print s 'blah As before, with print you see the contents of the string as it is (and as indeed it is also in the file that you saved). Just the single quote you added at the front of Blah. No double or single quotes or anything else. Now finally, let's try something a bit more elaborate. Do again: >>> os.system('notepad test.txt') Then put into the file the following 2 lines of text (notice the file now contains 2 lines, and both single and double quotes...): +++"+++This line is double quoted in the file and the quotes have + symbols around them.+++"+++ ---'---This line is single quoted in the file and the quotes have - symbols around them.---'--- Save it, exit Notepad, then do: >>> f=open('test.txt', 'r+') >>> s=f.read() >>> f.close() >>> s '+++"+++This line is double quoted in the file and the quotes have + symbols around them.+++"+++\n---\'---This line is single quoted in the file and the quotes have - symbols around them.---\'---\n' >>> print s +++"+++This line is double quoted in the file and the quotes have + symbols around them.+++"+++ ---'---This line is single quoted in the file and the quotes have - symbols around them.---'--- Notice we read both lines in the file into one single string. See how Python formats that as a string object, and escapes not only the single quotes but also the line break characters (\n). See also when Python is asked to "print" the string, you can see the escape characters really there. See what's happened? Do you understand why? Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
Correction on my last paragraph on my last mail: "See also when Python is asked to "print" the string, you can see the escape characters really there." -> "See also when Python is asked to "print" the string, you can see the escape characters aren't part of the actual contents of the string." ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: wierd replace problem
On Wed, 15 Sep 2010 07:20:33 am Walter Prins wrote: > Correction on my last paragraph on my last mail: > "See also when Python is asked to "print" the string, you can see the > escape characters really there." -> "See also when Python is asked to > "print" the string, you can see the escape characters aren't part of > the actual contents of the string." I think that half of the confusion here is that people are confused about what escape characters are. When you read text from a file, and Python sees a backslash, it DOESN'T add a second backslash to escape it. Nor does it add quotation marks at the start or end. Text is text. The characters you read from a text file -- or the bytes you read from any file -- remain untouched, exactly as they existed in the file. But what changes is the DISPLAY of the text. When you have the four characters abcd (with no quotation marks) and you ask Python to display it on the command line, the display includes punctuation, in this case quotation marks, just like a list includes punctuation [,] and a dict {:,}. If the string includes certain special characters like newlines, tabs, backslashes and quotation marks, the display uses escape codes \n \t \\ \' or \" as punctuation to the display only. But the extra backslashes don't exist in the string, any more than lists include items [ and ]. When you enter string literals, the way to enter them is by typing the display form. The display form includes matching quotation marks at the beginning and end, and escaping special characters. But that punctuation isn't part of the string. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] (no subject)
Hi! I have a problem. I just started python. when I use (open) function, is the file supposed to open? Because it doesn't. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
On Wed, Sep 15, 2010 at 1:38 AM, Sukhpal Saini wrote: > Hi! I have a problem. I just started python. when I use (open) function, > is the file supposed to open? Because it doesn't. > f = open('filename', 'r') opens the file in read-only format. There are others like binary, write, append etc. Check the manual for that. To read it you need to use read() or readline() Ex, s = f.read() Now s will be a string containing the contents of file. > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- ~l0nwlf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
"Sukhpal Saini" wrote Hi! I have a problem. I just started python. when I use (open) function, is the file supposed to open? Because it doesn't. How do you know? Are you also new to programming? Or do you know another programming language? Assuming that you are new to programming Are you expecting a window to appear with the file displayed? If so you will be disappointed, open() simply makes the file available to your program to manipulate. Any display of the file is down to you as the programmer. See the Handling Files topic of my tutorial for more information. OTOH If you realized that but genuinely believe that open() is not returning an open file object then you will need to give us some more context - ideally some sample code and any error messages. Please tell us which OS you are using too. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] wierd replace problem
"Steven D'Aprano" wrote OK,. Thats replacing a double slash in the data Er, surely not... I think you've confused backslashes and forward slashes. Or something. '\\' is a single backslash, not a double, because the first backslash is the escape character. A double backslash can be written ''. Erk, you are right of course, he would need to use a raw string to do it with a literal double slash. Silly me. However, based on his post I still think his issue may be one of represention not content. Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] input problem
"ANKUR AGGARWAL" wrote Suppose i am taking input or various variables like a=raw_input("...") //hello b=raw_input("")//hi but i want to run a common function when input is hello so instead of if a=="hello": fun() then again for b and then again for c then d and so on i have to apply the code for the specific variable , i want to run the function whenever in the code input is "hello" i am wondering is there is any way like if input=="hello": fun() I don;t see how that changes from the previous example except you changed a to input? However I think you are asking about processing a collection of data values (which happen to have been produced by raw_input() but could equally have been read from a file). The pattern for that case is the for loop: for data in data_collection: if data == "hello": fun() Or if you want to collect the results: results = [fun() for data in data_collection if data == "hello"] How you get the data into data_collecton I leave as an excercise! :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how best to implement paginated data in CLI
"Rance Hall" wrote I'm using python 3.1 with py-postgresql (located at http://python.projects.postgresql.org/ I need to work through how best to paginate larger sql result sets. Its usually best to do that at the SQL level by controlling the cursor. I don't know PostGres but most SQL dialects allow you to control the number of result rows returned to the cursor then fetch the next group and the next etc. This will also potentially save a lot of network bandwidth (you only fetch the results you need which may not be all of them) and get your results back quicker for a big result set. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] help with integers
Hi When I enter myvar= raw_input ("Please excuse a number of movies: ") and I try and convert it to an integer it gives me an error message. I put in: movietotal= int("myvar")* 3 and I get an error message Ciera ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with integers
On Tue, Sep 14, 2010 at 8:00 PM, Ciera Jones wrote: > Hi > When I enter myvar= raw_input ("Please excuse a number of movies: ") > and I try and convert it to an integer it gives me an error message. > I put in: > movietotal= int("myvar")* 3 and I get an error message > Ciera > post your code.. and also windows/linux/mac? if you post code and error message it will be easier to help > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with integers
"Ciera Jones" wrote When I enter myvar= raw_input ("Please excuse a number of movies: ") and I try and convert it to an integer it gives me an error message. I put in: movietotal= int("myvar")* 3 and I get an error message Don't put quotes around the variable name. Python is trying to convert the string "myvar" to an int, which it can't. BTW When posting it is best to send the code plus entire error message, it greatly helps us debug the problem. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Writing to Sound
Greetings tutors. First off, here is what I'm doing. I'm taking pi (3.141592 etc. etc. etc.), taking two values at a time, and then mapping the two values to pitch and length. I'm then using winsound.Beep to beep for x ms, at y frequency. What I want to do, is write that to file. Judging from http://codingmess.blogspot.com/2008/07/how-to-make-simple-wav-file-with-python.html, it seems to be more complex than I care to undertake without exploring the possibilities. Are there any simpler or higher level ways? I wouldn't mind something like sound_file.write(freq, length) like Beep does, but that may or may not exist. I dunno, a simple google doesn't yield anything. Thanks! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] list dll functions?
Hi all, Out of curiosity: I know I can call dll functions from python using the win32 lib, but is there any way to simply "examine" a loaded dll to see all of the functions and attributes it exposes for use? I would do no good with a hex editor since I have no idea what all the numbers mean, so I am hoping for a plaintext representation of a dll's possibilities and am most comfortable in Python. I am running the latest 2.6 on win7. TIA. -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com; http://www.facebook.com/mehgcap ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list dll functions?
> the win32 lib, but is there any way to simply "examine" a loaded dll > to see all of the functions and attributes it exposes for use? I would http://www.dependencywalker.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how best to implement paginated data in CLI
On Tue, Sep 14, 2010 at 7:15 PM, Alan Gauld wrote: > > "Rance Hall" wrote > >> I'm using python 3.1 with py-postgresql (located at >> http://python.projects.postgresql.org/ >> >> I need to work through how best to paginate larger sql result sets. > > Its usually best to do that at the SQL level by controlling the cursor. > I don't know PostGres but most SQL dialects allow you to control > the number of result rows returned to the cursor then fetch the next > group and the next etc. This will also potentially save a lot of network > bandwidth (you only fetch the results you need which may not be > all of them) and get your results back quicker for a big result set. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ Alan: I think I need to refine my definition of large in my original question. You are correct, but I think some more context might be in order. A standard windows terminal window opens to run my app and it has anywhere between 15 and 20 lines of text available for output. (that can be altered I know, but that has limits) Some of those lines are taken up with formatting and the question and input prompt at the bottom, so you have only room for 10 data elements from your list, In my case large is any recordset larger than the ten there is room for on a single screen. So the real question is how large is large? I'm operating under the assumption that the size of the datasets Im talking about are "small" in terms of what I usually think of when I think of databases and networking, bandwidth and the like. But large in terms of the delivery mechanism (the windows terminal window) I suspect that the extra network activity required to manage cursors on a remote database is in my case meaningful. I hope this sort of helps explain why I went where I went with my OP. In reviewing the app I'm hoping to replace I found the size of the client list is under 100 records. Given this new information, do you still think that db cursors is the way to go? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] selecting elements from dictionary
dear group: I have a dictionary object that looks like this: xdic {11135457: [1], 11135492: [1], 11135913: [1], 11135436: [1, 2], 11135699: [1, 2], 11135702: [1, 3], 11135901: [1]} I want to print only those items that have [1,2] and [1,3] in any order, such as [1,2] or [2,1], [3,1] or [1,3] >>> for item in xdic.keys(): ... if [1,2] in xdic[item]: ... print item I get a wrong answer, I know the values are there. How can I print only those item that have [1,2] and [1,3] Thank you. h ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list dll functions?
On 9/14/10, R. Alan Monroe wrote: >> the win32 lib, but is there any way to simply "examine" a loaded dll >> to see all of the functions and attributes it exposes for use? I would > > http://www.dependencywalker.com/ A great program, thanks! Best of all, for me anyway, it works well (so far) with JAWS, my screen reader. It is increasingly rare to find fully accessible programs nowadays, and I am glad that this one works. Now I just have to figure out how to see the expected arguments of a function, but I am sure that is in the manual somewhere... > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com; http://www.facebook.com/mehgcap ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] selecting elements from dictionary
xdic {11135457: [1], 11135492: [1], 11135913: [1], 11135436: [1, 2], 11135699: [1, 2], 11135702: [1, 3], 11135901: [1]} I want to print only those items that have [1,2] and [1,3] in any order, such as [1,2] or [2,1], [3,1] or [1,3] >>> for item in xdic.keys(): ... if [1,2] in xdic[item]: ... print item You can loop over the values directly: xdic = {11135457: [1], 11135492: [1], 11135913: [1], 11135436: [1, 2], 11135699: [1, 2], 11135702: [1, 3], 11135901: [1]} for values in xdic.values(): if len(values) == 2: print values or if you only want values which contain 1 and 2 or 3: for values in xdic.values(): if 1 in values and 2 in values or 3 in values: print values or a combination of the above, where you check the length and the content of the list. HTH, Jan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor