[Tutor] List weirdness
Hi, I was wondering why this happens. I was trying to create a list of lists. >>> d = [[]] >>> d[0][0]=1 Traceback (most recent call last): File "", line 1, in ? IndexError: list assignment index out of range >>> d [[]] What's wrong with that? However: >>> d[0].append(1) >>> d [[1]] I guess I can't reference [0] on an empty list. (I come from a C background.) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List weirdness
"Moos Heintzen" wrote >>> d = [[]] >>> d[0][0]=1 IndexError: list assignment index out of range >>> d[0].append(1) >>> d [[1]] I guess I can't reference [0] on an empty list. Thats right. You can't assign a value to a position in a list that hasn't been created yet. It has nothing to do with nesting, its the same for a simople lust: lst = [] lst[0] = 66 Traceback (most recent call last): File "", line 1, in IndexError: list assignment index out of range lst.append(66) lst [66] You can also use insert, which takes an index. But if the index is non existent it appends... lst2 = [] lst2.insert(3,66) lst2 [66] lst.insert(3,66) lst [66, 66] HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Keeping Dictonary Entries Ordered
Le Fri, 13 Feb 2009 15:41:01 +1300, John Fouhy a écrit : > 2009/2/13 Eric Dorsey : > > Alan, can you give a short snippet of what that would look like? I was > > trying to code out some idea of how you'd retain insertion order using > > another dict or a list and didn't get anywhere. > > Here's something basic: > > class o_dict(dict): > def __init__(self, *args, **kw): > dict.__init__(self, *args, **kw) > self.__keylist = [] > > def __setitem__(self, key, val): > dict.__setitem__(self, key, val) > if key not in self.__keylist: > self.__keylist.append(key) > > def __iter__(self): > return iter(self.__keylist) > > It will do the right thing if you do 'for key in odict:', but not for > things like iteritems(). It will break if you delete keys from the > dictionary, and the 'key not in self.__keylist' test will get slow if > you have lots and lots of keys. It will also not do what you want if > you initialise it as something like: o_dict(foo=1, bar=2) An issue is that obviously you can't initialize an ordered dict from another dict or a set of keyword arguments, for those are unordered. So I simply took **kwargs off the __init__ method. And let as single possible init stuff a list of (key,value) pairs. Also, as a built_in dict accepts only a single arg, there is no need for *arg: the seq of pairs must be contained in a list or tuple. From the pairs can then the keylist be properly initialised. This led me to something similar to the following: class Ordict(dict): def __init__(self, pairs): dict.__init__(self, pairs) self._keylist = [k for (k,v) in pairs] def __setitem__(self, key, val): dict.__setitem__(self, key, val) if key not in self._keylist: self._keylist.append(key) def __iter__(self): return iter(self._keylist) def __str__(self): pair_texts = ["%s:%s" % (k,self[k]) for k in self._keylist] return "[%s]" % ", ".join(pair_texts) od = Ordict([('a',1), ('d',4), ('b',2)]) od[' '] = 0 ; od['c'] = 3 print od._keylist for k in od: print "%s: %s " % (k,od[k]), print; print od ==> ['a', 'd', 'b', ' ', 'c'] a: 1d: 4b: 2 : 0c: 3 [a:1, d:4, b:2, :0, c:3] I remember there were some more minor issues. Denis -- la vida e estranya ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python
Dear Tutor, I am preparing a data base saving it with pickle. I want to add additional information to the data base but seem to to have to recover the whole file from disc then add to it and save it again. Is there and append function within Pickle that will add information to the end of an existing file, similar to the append fuction used with text files, without recovering the file from the disc. The data file will eventually be quite large and I can see a time coming when there will be a time delay problem. Look forward to your help, Regards Philip cooper ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python
On Fri, Feb 13, 2009 at 5:37 AM, Philip Cooper wrote: > Dear Tutor, > > I am preparing a data base saving it with pickle. I want to add additional > information to the data base but seem to to have to recover the whole file > from disc then add to it and save it again. Is there and append function > within Pickle that will add information to the end of an existing file, > similar to the append fuction used with text files, without recovering the > file from the disc. The data file will eventually be quite large and I can > see a time coming when there will be a time delay problem. Pickle loads and saves whole objects. You can have multiple objects in one file but if one object changes you have to re-write the file. So if your database object is for example a big dict in which you are changing or adding elements, you will have to rewrite the whole dict. The shelve module provides a persistent dict that might be better suited to what you are doing. But it sounds like you might be well served by using a real database such as SQLite, which comes with recent versions of Python. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] extracting phrases and their memberships from syntax trees
On Thu, Feb 12, 2009 at 6:20 PM, Emad Nawfal (عماد نوفل) wrote: > Dear Tutors, > I have syntax trees like the one below. I need to extract the membership > information like which adjective belongs to which noun phrase, and so on. In > short, I want to do something like this: > http://ilk.uvt.nl/team/sabine/chunklink/README.html > I already have the Perl script that does that, so I do not need a script. I > just want to be able to do this myself. My question is: what tools do I need > for this? Could you please give me pointers to where to start? I'll then try > to do it myself, and ask questions when I get stuck. I guess I'm in the mood for writing parsers this week :-) Attached is a parser that uses PLY to parse the structure you provided. The result is a nested list structure with exactly the same structure as the original; it builds the list you would get by replacing all the () with [] and quoting the strings. Also in the attachment is a function that walks the resulting tree to print a table similar to the one in the chunklink reference. This is a pretty simple example of both PLY usage and recursive walking of a tree, if anyone wants to learn about either one. I hope I haven't taken all your fun :-) Kent PS to the list: I know, I'm setting a bad example. Usually we like to teach people to write Python, not write their programs for them. ''' Parse files in Penn Treebank II format See http://ilk.uvt.nl/team/sabine/chunklink/README.html and http://bulba.sdsu.edu/jeanette/thesis/PennTags.html The output is a nested list structure directly corresponding to the structure of the input, as if all the () were replaced with [] and the other text was quoted ''' from pprint import pprint from ply import lex, yacc debug = 0 text = """ ( (S (NP-SBJ-1 (NP (NNP Rudolph) (NNP Agnew) ) (, ,) (UCP (ADJP (NP (CD 55) (NNS years) ) (JJ old) ) (CC and) (NP (NP (JJ former) (NN chairman) ) (PP (IN of) (NP (NNP Consolidated) (NNP Gold) (NNP Fields) (NNP PLC) (, ,) ) (VP (VBD was) (VP (VBN named) (S (NP-SBJ (-NONE- *-1) ) (NP-PRD (NP (DT a) (JJ nonexecutive) (NN director) ) (PP (IN of) (NP (DT this) (JJ British) (JJ industrial) (NN conglomerate) )) (. .) )) """ # Lexical tokens tokens = ( 'TOKEN', ) literals = "()" # Regular expression rules for simple tokens t_TOKEN = r'[^\(\)\s]+' # A string containing ignored characters (spaces and tabs) t_ignore = ' \t\r\n' # Error handling rule def t_error(t): print "Illegal character '%s'" % t.value[0] t.lexer.skip(1) # Build the lexer lexer = lex.lex() def p_tree(p): '''tree : '(' TOKEN TOKEN ')' | '(' TOKEN list ')' | '(' list ')' ''' if len(p) == 4: p[0] = [p[2]] else: p[0] = [p[2], p[3]] def p_list(p): '''list : tree | list tree ''' if len(p) == 2: p[0] = [p[1]] else: p[0] = p[1] + [p[2]] parser = yacc.yacc() def list_leaf_nodes(tree, path = []): ''' Print all the leaves of tree inorder with their parent tags ''' if len(tree) == 1: # Root node has only one element list_leaf_nodes(tree[0], []) else: if isinstance(tree[1], list): # Show child nodes itemPath = path + [tree[0]] for item in tree[1]: list_leaf_nodes(item, itemPath) else: # Show leaf node print '%-8s %-8s %s' % (tree[0], tree[1], format_path(path)) def format_path(path): return '/'.join(item.split('-')[0] for item in path) if __name__ == '__main__': tree = parser.parse(text, debug=debug) #pprint(tree) list_leaf_nodes(tree) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] *nix tail -f multiple log files with Thread
Hi everyone, I copied a program from C to track multiple log files. I would like to be able to print a label when a log file is updated. Here is the program; #!/usr/bin/python from threading import Thread import subprocess from Queue import Queue num_threads = 3 queue = Queue() logfiles = ["/var/log/messages", "/var/log/apache2/access_log", "/var/log/apache2/error_log"] def logtailer(i, q,): while True: lfile = q.get() sudo = "sudo" tail = "tail" arg = "-f" ret = subprocess.call([sudo, tail, arg, lfile]) q.task_done() for i in range(num_threads): worker = Thread(target=logtailer, args=(i, queue)) worker.setDaemon(True) worker.start() for lfile in logfiles: queue.put(lfile) queue.join() And here is a sample of the output; [Fri Feb 13 08:58:48 2009] [error] [client 127.0.0.1] File does not exist: /var/www/localhost/htdocs/moodle/favicon.ico [Fri Feb 13 08:58:51 2009] [error] [client 127.0.0.1] File does not exist: /var/www/localhost/htdocs/moodle/favicon.ico Feb 13 09:02:26 opteron sudo:david : TTY=pts/4 ; PWD=/home/david ; USER=root ; COMMAND=/bin/tail -f /var/log/apache2/error_log Feb 13 09:02:26 opteron sudo: pam_unix(sudo:session): session opened for user root by david(uid=0) Feb 13 09:02:26 opteron sudo: pam_unix(sudo:session): session closed for user root Feb 13 09:10:01 opteron cron[10633]: (root) CMD (test -x /usr/sbin/run-crons && /usr/sbin/run-crons ) Feb 13 09:18:33 opteron su[10678]: Successful su for root by david Feb 13 09:18:33 opteron su[10678]: + pts/6 david:root Feb 13 09:18:33 opteron su[10678]: pam_unix(su:session): session opened for user root by david(uid=1000) 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET /theme/custom_corners/favicon.ico HTTP/1.1" 200 894 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET /lib/speller/spellChecker.js HTTP/1.1" 200 15980 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET / HTTP/1.1" 200 13718 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET /theme/custom_corners/styles.php HTTP/1.1" 200 30709 I would like to be able to add a label like; [Fri Feb 13 08:58:48 2009] [error] [client 127.0.0.1] File does not exist: /var/www/localhost/htdocs/moodle/favicon.ico [Fri Feb 13 08:58:51 2009] [error] [client 127.0.0.1] File does not exist: /var/www/localhost/htdocs/moodle/favicon.ico Feb 13 09:02:26 opteron sudo:david : TTY=pts/4 ; PWD=/home/david ; USER=root ; COMMAND=/bin/tail -f /var/log/apache2/error_log Feb 13 09:02:26 opteron sudo: pam_unix(sudo:session): session opened for user root by david(uid=0) Feb 13 09:02:26 opteron sudo: pam_unix(sudo:session): session closed for user root Feb 13 09:10:01 opteron cron[10633]: (root) CMD (test -x /usr/sbin/run-crons && /usr/sbin/run-crons ) Feb 13 09:18:33 opteron su[10678]: Successful su for root by david Feb 13 09:18:33 opteron su[10678]: + pts/6 david:root Feb 13 09:18:33 opteron su[10678]: pam_unix(su:session): session opened for user root by david(uid=1000) 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET /theme/custom_corners/favicon.ico HTTP/1.1" 200 894 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET /lib/speller/spellChecker.js HTTP/1.1" 200 15980 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET / HTTP/1.1" 200 13718 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET /theme/custom_corners/styles.php HTTP/1.1" 200 30709 I can create the label like this; def label() print "<%s\n>" % lfile But I have no idea how to get it to work when a thread is updated. thanks -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] extracting phrases and their memberships from syntax
Pyparsing has a built-in helper called nestedExpr that fits neatly in with this data. Here is the whole script: from pyparsing import nestedExpr syntax_tree = nestedExpr() results = syntax_tree.parseString(st_data) from pprint import pprint pprint(results.asList()) Prints: [[['S', ['NP-SBJ-1', ['NP', ['NNP', 'Rudolph'], ['NNP', 'Agnew']], [',', ','], ['UCP', ['ADJP', ['NP', ['CD', '55'], ['NNS', 'years']], ['JJ', 'old']], ['CC', 'and'], ['NP', ['NP', ['JJ', 'former'], ['NN', 'chairman']], ['PP', ['IN', 'of'], ['NP', ['NNP', 'Consolidated'], ['NNP', 'Gold'], ['NNP', 'Fields'], ['NNP', 'PLC'], [',', ',']], ['VP', ['VBD', 'was'], ['VP', ['VBN', 'named'], ['S', ['NP-SBJ', ['-NONE-', '*-1']], ['NP-PRD', ['NP', ['DT', 'a'], ['JJ', 'nonexecutive'], ['NN', 'director']], ['PP', ['IN', 'of'], ['NP', ['DT', 'this'], ['JJ', 'British'], ['JJ', 'industrial'], ['NN', 'conglomerate']]], ['.', '.' If you want to delve deeper into this, you could, since the content of the () groups is so regular. You in essence reconstruct nestedExpr in your own code, but you do get some increased control and visibility to the parsed content. Since this is a recursive syntax, you will need to use pyparsing's mechanism for recursion, which is the Forward class. Forward is sort of a "I can't define the whole thing yet, just create a placeholder" placeholder. syntax_element = Forward() LPAR,RPAR = map(Suppress,"()") syntax_tree = LPAR + syntax_element + RPAR Now in your example, a syntax_element can be one of 4 things: - a punctuation mark, twice - a syntax marker followed by one or more syntax_trees - a syntax marker followed by a word - a syntax tree Here is how I define those: marker = oneOf("VBD ADJP VBN JJ DT PP NN UCP NP-PRD " "NP NNS NNP CC NP-SBJ-1 CD VP -NONE- " "IN NP-SBJ S") punc = oneOf(", . ! ?") wordchars = printables.replace("(","").replace(")","") syntax_element << ( punc + punc | marker + OneOrMore(Group(syntax_tree)) | marker + Word(wordchars) | syntax_tree ) Note that we use '<<' operator to "inject" the definition of a syntax_element - we can't use '=' or we would get a different expression than the one we used to define syntax_tree. Now parse the string, and voila! Same as before. Here is the entire script: from pyparsing import nestedExpr, Suppress, oneOf, Forward, OneOrMore, Word, printables, Group syntax_element = Forward() LPAR,RPAR = map(Suppress,"()") syntax_tree = LPAR + syntax_element + RPAR marker = oneOf("VBD ADJP VBN JJ DT PP NN UCP NP-PRD " "NP NNS NNP CC NP-SBJ-1 CD VP -NONE- " "IN NP-SBJ S") punc = oneOf(", . ! ?") wordchars = printables.replace("(","").replace(")","") syntax_element << ( punc + punc | marker + OneOrMore(Group(syntax_tree)) | marker + Word(wordchars) | syntax_tree ) results = syntax_tree.parseString(st_data) from pprint import pprint pprint(results.asList()) -- Paul ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Copy file function works, but not with adding the date copied
Hello, I am modifying a simple program "copy file" from the tutorials Alan Gauld wrote. In it's first simpler instance (W/O date) it works beautifully. But I wanted to add the date the file was copied. I've kept it simple by pointing to a single file. The problem lies somewhere in how the program modifies the information. It creates the new copied file, but can't open with the application TextEdit. However, I can read the file from the shell interpreter and do see the date the file was copied: The date this file was copied Friday February 13 {\rtf1\mac\ansicpg1\cocoartf824\cocoasubrtf440 {\fonttbl\f0\fnil\fcharset77 LucidaGrande;\f1\fnil\fcharset77 Verdana; \f2\fmodern\fcharset77 Courier; \f3\fswiss\fcharset77 Helvetica;\f4\fnil\fcharset77 LucidaGrande-Bold; \f5\fswiss\fcharset77 ArialMT; } {\colortbl;\red255\green255\blue255;\red249\green249\blue249;\red51 \green51\blue51;} \margl1440\margr1440\vieww14060\viewh10300\viewkind0 \deftab720 \pard\pardeftab720\sl320\ql\qnatural \f0\fs24 \cf0 \ tcpdump -q -ien1lists tcp activity reatime\ \ ps axc -U rootLists processes by "root" users\ \ \ I'm using 2.61 on OS X 10.4.11. My apologies in advance for the indention format. TIA, Pat below is the file: # this is a simple tool to copy a file from the console (modified to show the date it was copied). import time inp = open( "/Users/pw/Desktop/Terminal_commands.rtf","r") # file to be opened using the path outp = open( "/Users/pw/Desktop/Terminalback_commands.rtf","w") # Copied file modified name today = time.localtime(time.time()) #Using the time function to output the date file was copied theDate = time.strftime("%A %B %d", today) outp.write( "The date this file was copied %s\n\n" % theDate) for line in inp: outp.write(line) print "This copied file has now been modified only by the date copied." inp.close() outp.close()___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List weirdness
Moos Heintzen wrote: Hi, I was wondering why this happens. I was trying to create a list of lists. >>> d = [[]] >>> d[0][0]=1 Traceback (most recent call last): File "", line 1, in ? IndexError: list assignment index out of range >>> d [[]] What's wrong with that? However: >>> d[0].append(1) >>> d [[1]] I guess I can't reference [0] on an empty list. (I come from a C background.) Can you have an empty array in C? If so, it does not have any elements, so you can't refer to element 0. -- Bob Gailer Chapel Hill NC 919-636-4239 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Calling variable from two different classes
I want to be able to call a variable from one of my classes to my main class (interface layout) and have it update every minute. I am using Python and wxPython. Is it better to be in the main class and read the variable or should I have the class the variable resides in to send the variable along to the main class? In my interface class I have it as: display = wx.StaticText(self, -1, '', (50, 50)) while the class where the variable is in: data_rate = 5000 and I want to be able to put the value stored in data_rate into display so that I can show it on my interface. And regarding the update per some time, I am looking into the poll command. Is that the direction where I should be heading? (I know updating data_rate won't do anything right now since it's a constant, but it will vary later on... just one step at a time here). ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Copy file function works, but not with adding the date copied
wrote I am modifying a simple program "copy file" from the tutorials Alan Gauld wrote. In it's first simpler instance (W/O date) it works beautifully. But I wanted to add the date the file was copied. I've kept it simple by pointing to a single file. The problem lies somewhere in how the program modifies the information. It creates the new copied file, but can't open with the application TextEdit. The date this file was copied Friday February 13 {\rtf1\mac\ansicpg1\cocoartf824\cocoasubrtf440 The problem is that this is an RTF format which is a binary format. You can process binary data ion Python (see the box on the files topic page) but it is much more difficult that normal plain text files. So you have written a line of plain text at the front of the RTF file and the word processor doesn't know how to interpret that their. So it ignores it! import time inp = open( "/Users/pw/Desktop/Terminal_commands.rtf","r") # file to Open a plain text file (eg foo.txt) instead of an RTF file. That should work. Unfortunatey reading and writing RTF files is a much more advanced topic than you might expect, too much for your level of skill just now. By the time you've completed the tutorial you might be ready to try :-) Also I think there is a Python module somewhere for reading/writing RTF files if that is a real need that you have. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List weirdness
On Fri, Feb 13, 2009 at 11:01 AM, bob gailer wrote: > Moos Heintzen wrote: > >> I guess I can't reference [0] on an empty list. (I come from a C >> background.) >> > Can you have an empty array in C? If so, it does not have any elements, so > you can't refer to element 0. I think the OP was confusing an empty array in C (something like int foo[10] = {}; ) where memory is allocated, just not "used", to an empty list in Python. AFAIK, creating an empty list in python is a lot more similar to creating an empty vector in C++. -Wayne ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Calling variable from two different classes
"Hi" wrote I want to be able to call a variable from one of my classes to my main class (interface layout) and have it update every minute. Sp provuide an update method in the class that has the variable. Do not pass the variable to another class to update it, Objects should always do it to themselves. wxPython. Is it better to be in the main class and read the variable or should I have the class the variable resides in to send the variable along to the main class? Neither its better for the mainclass to update the variable by sending a message to the class with the variable. Now the next question is what determines when it needs to be updated? In Python reading the data from a class is considered OK - in most OOP languages its considered better to write a "getter" method. But if you need to display and set it in your main class are you sure the variable shouldn't be stored in the main class? Is it part of the display or part of the underlying logic that the GUI is controlling? If the latter I'd go for using a getter and an update method but if its just a display feature move it to the main class. What you really want to eliminate is any knowledge of the GUI in the application classes. A little bit of knowledge of the app classes by the GUI is not so bad. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Copy file function works, but not with adding the date copied
On Fri, Feb 13, 2009 at 11:11 AM, Alan Gauld wrote: > >> {\rtf1\mac\ansicpg1\cocoartf824\cocoasubrtf440 >> > > The problem is that this is an RTF format which is a binary format. > You can process binary data ion Python (see the box on the files > topic page) but it is much more difficult that normal plain text files. > I'd like to correct a misapprehension here: RTF files are not a "binary format" in the usual sense of that phrase - there are no non-ASCII characters, newlines are handled normally, etc. They're text files, but with lots of funky formatting codes included - which are themselves all text. They're a lot like badly-formatted, insanely complicated XML, actually. They're full of gibberish-looking strings like the above, and the nesting of curly braces can run to dozens of layers deep - however, if you want to get a quick idea of what's going on in an RTF, the fastest way is to unfold it (search-and-replace each "{" and "}" with "{\n" and "}\n" respectively) and indent each opened curly brace. Then if you want to give yourself a headache, you can sit down with Microsoft's RTF specification and figure out what all those codes do. -- www.fsrtechnologies.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Copy file function works, but not with adding the date copied
On Fri, Feb 13, 2009 at 11:35 AM, Marc Tompkins wrote: > On Fri, Feb 13, 2009 at 11:11 AM, Alan Gauld wrote: > >> >>> {\rtf1\mac\ansicpg1\cocoartf824\cocoasubrtf440 >>> >> Here's a quick-and-dirty way to do what (I think) you want to do: Skip the first curly brace ("{") - find the next one. Just before it, insert a space + the datestamp text. That's it. Now if you open the RTF file in Word, or WordPad, or whatever RTF reader you have on your system, your text will appear (in the system-default font and style, 'cause you inserted it before any document styles) at the top of the document. Note: this is absolutely NOT valid RTF; it only works because Microsoft specifically requires that RTF readers obey Posten's Law. If you later edit the modified file in Word, WordPad, etc. your datestamp text will be moved to a more appropriate area of the file and you might have a hard time finding it again. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Loops
I need some help. I have written a filter called Peqibot that takes posts from Twitter and makes them into wikipages on peqipedia.com So if you post the following message on Twitter: >@peqi Tallinn=The capital city of [[Estonia]]. It makes a page on peqipedia.com with "Tallinn" as the headline and with the article text being "The captial city of [[Estonia]]." ... it seems to be working ok - but I discovered that if someone posts a message starting with "@peqi" but without an "=" sign the program crashes. The way I have come up with to solve this problem is to put the following loop in: >> rawfeed = feedparser(http//twitter.com/foobar) >> feedstring = rawfeed.split('=',1)#this splits the feed at the first >> "=" >> headline = feedstring[0]#this is the text infront of the >> "=" sign. >> if len(headlinestring) == len(rawfeed)#ie. if the split hasn't worked >> they will be exactly the same length >> body = "\x7b\x7bEmpty\x7d\x7d"#this adds an "{{Empty}}" template >> to the wiki >> else: >> body = feedstring[1] >> #here I use urllib to encode a post from headline and body that can be >> posted to the wiki. But I can't get it to work - I have tried various indents and break and continues - but I don't know enough about loops to identify what I have done wrong. Any advice or suggestions would be great. (it's my first program so there might well be a better way to avoid this problem in the first place). Best wishes Payo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Variable to String?
Title: Signature.html That's pretty much the question in Subject. I've got a date time variable with, for example, 15:00:00 in hh:mm:ss format, and I'd like to make it a string. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) S, quiet. I'm thinking about filling this space. Web Page:___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Variable to String?
On Fri, Feb 13, 2009, Wayne Watson wrote: > > That's pretty much the question in Subject. I've got a date time > variable with, for example, 15:00:00 in hh:mm:ss format, and I'd like > to make it a string. The easiest way is probably to use the strftime method available on any datetime object. It uses the standard strftime expansion, which on any Linux/Unix box will be found with ``man strftime''. 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 Scientists are explorers. Philosophers are tourists. -- Richard Feynman ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Variable to String?
On Fri, Feb 13, 2009 at 6:50 PM, Wayne Watson wrote: > That's pretty much the question in Subject. I've got a date time variable > with, for example, 15:00:00 in hh:mm:ss format, and I'd like to make it a > string. Lots of choices: In [1]: from datetime import datetime In [2]: d=datetime.now() In [4]: str(d) Out[4]: '2009-02-13 19:03:43.517789' In [6]: d.isoformat() Out[6]: '2009-02-13T19:03:43.517789' strftime() takes a format string so you can get pretty much whatever format you want: In [7]: d.strftime("%a, %d %b %Y %H:%M:%S +") Out[7]: 'Fri, 13 Feb 2009 19:03:43 +' Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Variable to String?
On Fri, Feb 13, 2009 at 3:50 PM, Wayne Watson wrote: > That's pretty much the question in Subject. I've got a date time variable > with, for example, 15:00:00 in hh:mm:ss format, and I'd like to make it a > string. >>> import datetime >>> d = datetime.time(15,0) datetime.time(15, 0) >>> d datetime.time(15, 0) >>> str(d) '15:00:00' is this what you're looking for, or was there something else? -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Copy file function works, but not with adding the date copied
"Marc Tompkins" wrote Here's a quick-and-dirty way to do what (I think) you want to do: Skip the first curly brace ("{") - find the next one. Just before it, insert a space + the datestamp text. That's it. If the OP is just working through my tutor I doubt if he will be able to do much of that yet. Especially since the "handling text" topic is the one *after* handling files! :-) BTW Thanks for the reminder about RTF format, you are right it is not strictly a binary file it is formatted text. The end result is the same in that the OP needs to use a plain unformatted text file rather than trying to write to RTF. Also The RTF module I mentioned is here: http://www.nava.de/2005/04/06/pyrtf/ HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Loops
"pa yo" wrote The way I have come up with to solve this problem is to put the following loop in: rawfeed = feedparser(http//twitter.com/foobar) feedstring = rawfeed.split('=',1)#this splits the feed at the first "=" headline = feedstring[0]#this is the text infront of the "=" sign. if len(headlinestring) == len(rawfeed)#ie. if the split hasn't worked they will be exactly the same >>> body = "\x7b\x7bEmpty\x7d\x7d"#this adds an "{{Empty}}" template to the wiki else: body = feedstring[1] Sorry, where is the loop? But I can't get it to work - I have tried various indents and break and continues - but I don't know enough about loops to identify what I have done wrong. I'm confused, there is no loop only a conditional statement (if/else) The only loops supported in Python are for and while (OK you could count list comprehensions/generator expressions too) and neither of them are in your code. However you don't tell us what is happening that you don;t expect. Are you getting an error message? If so what (all of it please)? Or is it just the output that is different to what you expect? if so what did you expect and what did you get? And finally which version of Python and which OS please? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Copy file function works, but not with adding the date copied
cclpia...@comcast.net wrote: Hello, "but can't open with the application TextEdit" What are you doing to open it? What does "can't open" mean"? Error messages or what? Could this be a resource fork issue? AFAIK Python does not reproduce the resource fork. -- Bob Gailer Chapel Hill NC 919-636-4239 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Variable to String?
Title: Signature.html Well, let me try this again. I'm only interested in time. The user sees a widget dialog that asks him to put the time in it in the format HH:MM:YY, so he enters 15:30:10, or, as before 15:00:00. The value gets back to the code I'm working in as 15:30:10 as the type in Subject. I need to write the value to a file as a string, "15:30:10". In fact, I want to write it as start_time=15:30:10 in a txt file. Ah, this was as simple as using str(time_value), where time_value was of the aforementioned type. That's Kent's [4], and looked tempting for its simplicity. Too simple, I guess for me to try. str() had a little more umph that I thought. I had played around with the datetime module some many months for many combos of date+time, and anticipated having to beat against it again. Thankfully not here. :-) Good. Thanks. wesley chun wrote: On Fri, Feb 13, 2009 at 3:50 PM, Wayne Watson wrote: That's pretty much the question in Subject. I've got a date time variable with, for example, 15:00:00 in hh:mm:ss format, and I'd like to make it a string. import datetime d = datetime.time(15,0) datetime.time(15, 0) d datetime.time(15, 0) str(d) '15:00:00' is this what you're looking for, or was there something else? -- 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 -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) S, quiet. I'm thinking about filling this space. Web Page:___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor