[Tutor] Get user input in wxpython
Hi: I'm new to python and wxpython, and I'm trying to make a program to send mail. I'm using what follows: class MyFrame1(wx.Frame): def __init__(self, *args, **kwds): ... self.message = wx.TextCtrl(self.panel_1, -1, "") self.button_1 = wx.Button(self.panel_1, -1, "SEND Mail") ... # And then: wx.EVT_BUTTON(self,self.button_1.GetId(), self.Mail) # The Mail method is: def Mail(self,event): self.from = "[EMAIL PROTECTED]" self.host = "localhost" self.to = "[EMAIL PROTECTED]" self.body = self.message server = smtplib.SMTP(self.host) server.sendmail(self.from, [self.to], self.body) server.quit() But when pressing the Send Mail button I only get: TypeError: len() of unsized object Anybody knows what I'm doing wrong? Maybe I'm not getting the user input, or just dont know how to use that input in the Mail method... Because if I use: def Mail(self,event): self.from = "[EMAIL PROTECTED]" self.host = "localhost" self.to = "[EMAIL PROTECTED]" self.body = "any message" #as string everything works fine. server = smtplib.SMTP(self.host) server.sendmail(self.from, [self.to], self.body) server.quit() Thanks in advanced. Daniel Queirolo. __ Renovamos el Correo Yahoo! Nuevos servicios, más seguridad http://correo.yahoo.es ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] NotebookSizer is no longer needed
Hi... Well, I'm working on Gui programs with wxglade. On MS Windows I'm getting the following message: "DeprecationWarning: NotebookSizer is no longer needed" No message on Linux... and, if I remove the notebook sizer, then I cannot put any notebook at all, so I'm kind of lost in here... Anybody knows about this? :( My tree is like: Frame_1 Sizer_1 Notebook_1 Note_book_pane_1 Note_book_pane_2 So the Sizer_1 would be the "NotebookSizer". If I remove it, then I can't place a notebook, at least in wxglade. Anyhow, I know very little about wxpython... >From Chile, Daniel. __ Renovamos el Correo Yahoo! Nuevos servicios, más seguridad http://correo.yahoo.es ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] NotebookSizer is no longer needed
There is a good chance I got it all wrong... __ Renovamos el Correo Yahoo! Nuevos servicios, más seguridad http://correo.yahoo.es--- Begin Message --- Hi... Well, I'm working on Gui programs with wxglade. On MS Windows I'm getting the following message: "DeprecationWarning: NotebookSizer is no longer needed" No message on Linux... and, if I remove the notebook sizer, then I cannot put any notebook at all, so I'm kind of lost in here... Anybody knows about this? :( My tree is like: Frame_1 Sizer_1 Notebook_1 Note_book_pane_1 Note_book_pane_2 So the Sizer_1 would be the "NotebookSizer". If I remove it, then I can't place a notebook, at least in wxglade. Anyhow, I know very little about wxpython... >From Chile, Daniel. __ Renovamos el Correo Yahoo! Nuevos servicios, más seguridad http://correo.yahoo.es --- End Message --- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] AppendText as new lines
Hi, to all. Well, I have some list results that I must write to a Window. This is what I have tu show: (('Name1',), ('Name2',)) This is my "show function" def Listar_Mostrar(self,event): connect = MySQLdb.connect(host,user,passwd,db) cursor = connect.cursor() cursor.execute("SELECT nombres FROM apiterapia") result = cursor.fetchall() for record in result: self.text_ctrl_listar.AppendText(record[0]) The results are shown in the text window as: Name1Name2 And what I really want to do is something like this: Name1 Name2 Anybody knows how this can be done? Thanks to all of you. __ Renovamos el Correo Yahoo! Nuevos servicios, más seguridad http://correo.yahoo.es ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] From file2.py append an item to file1.py combobox
Hi to all: How can I append some data from file1.py to a combobox on file2.py? I know, if you want to append data to a combobox inside the same script, I would be like follows: # file1.py import wx class Myframe(wx.Frame): def __init__(self, *args, **kwds): ... self.mycombobox = wx.Combobox(... ... # and then... self.mycombobox.Append("Item") # would append to the combobox a new item. # file2.py # So here are my problems... # I got: import wx,file1 class Subframe(wx.Frame): def __init__(self, *args, **kwds) ... def Mymethod(self,event): file1.Myframe.mycombobox.Append("Item") # and it doesnt work... # file1.Myframe.self.mycombobox.Append("item") # does not work either.. What can I do? thanks in advance Daniel. __ Renovamos el Correo Yahoo! Nuevos servicios, más seguridad http://correo.yahoo.es ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Expanding _treeList in TreeCtrl
Hi to all, list: Well, I wanted to ask for some help on some subject. I have a TreeCtrl with a _treeList variable: _treeList = [ ( 'Parent 1', ['Child 1.1','Child 1.2'] ), ( 'Parent 2', [] ), ( 'Parent 3', [ 'Child 3.1', 'Child 3.2'] ), ( 'Parent 4', ['Child 4'] ) ] self.tree = wx.TreeCtrl(... self.root = self.tree.AddRoot("Main") # I make the menu with: for item in _treeList: child = self.tree.AppendItem(self.root, item[0]) for childItem in item[1]: self.tree.AppendItem(child, childItem) # Then expand the root self.tree.Expand(root) Now, I'm looking for some code that would expand all trees branches, and not just the root. And I don't seem to manage to code something like that. Any ideas on how this could be done? Thanks. Daniel __ Renovamos el Correo Yahoo! Nuevos servicios, más seguridad http://correo.yahoo.es ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Upgrading from Python 2.5 to Python 2.6 - IDLE not working...
Hi All, This is my first post, so I apologize in advance for any etiquette violations. I am interested in learning Python, and to that end, I undertook to upgrade my current version of Python 2.5 (available via openSUSE repositories and YaST) to Python 2.6. I have Python 2.6 running (compiled from source [I'm not a total bonehead]) but idle gives me the following when I invoke it in bash: [EMAIL PROTECTED]:~> idle Traceback (most recent call last): File "/usr/local/bin/idle", line 3, in from idlelib.PyShell import main File "/usr/local/lib/python2.6/idlelib/PyShell.py", line 14, in import macosxSupport File "/usr/local/lib/python2.6/idlelib/macosxSupport.py", line 6, in import Tkinter File "/usr/local/lib/python2.6/lib-tk/Tkinter.py", line 39, in import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter [EMAIL PROTECTED]:~> I thought of unistalling and reinstalling (using YaST) the associated Python packages to make them aware of the version change, but the Idle package says it requires Python 2.5.2, nothing more or less, so I didn't attempt it. Thanks in advance for your patience. Dan -- -=-=-=-=-=-=-=-=- Science is what we have learned about how not to fool ourselves about the way the world is. - Richard Feynman ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Working with lines from file and printing to another keeping sequential order
Dear Tutors, I have a file from which I want to extract lines that end in certain strings and print to a second file. More specifically, I want to: 1) iterate over each line in the file, and if it ends in "yes", print it. 2) move to the line following the one described in #1 above, and if it ends in, "no" print it. 3) move to third line, and if it ends in "no", print it. 4) move to fourth line, and if it ends in "no" discard it, but if it ends in "yes" repeat 1, 2, and 3 above. 5) move to fifth line, and if it ends in "no" discard it, but if it ends in "yes" repeat 1, 2, 3, and 4 above, and so on. The goal is to get a ratio of 1 to 2 "yes" to "no" lines from a file in such a way that keeps the order of the lines in output. An abstraction away from this so that any ratio of "yes" to "no" lines could be printed while keeping the order of the original lines would be great. I am new to Python and could not solve the problem. Your help is appreciated. Cheers, --dan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Working with lines from file and printing to another keeping sequential order
Hi Bob and tutors, Thanks Bob for your response! currently I have the current code, but it does not work: ListLines= [] for line in open('test.txt'): line = line.rstrip() ListLines.append(line) for i in range(len(ListLines)): if ListLines[i].endswith("yes") and ListLines[i+1].endswith("no") and ListLines[i+1].endswith("no"): print ListLines[i], ListLines[i+1], ListLines[i+2] elif ListLines[i].endswith("yes") and ListLines[i+1].endswith("no"): print ListLines[i], ListLines[i+1] elif ListLines[i].endswith("yes"): print ListLines[i] elif ListLines[i].endswith("no"): continue else: break I get the following error: Traceback (most recent call last): File "test.py", line 18, in if ListLines[i].endswith("yes") and ListLines[i+1].endswith("no") and ListLines[i+1].endswith("no"): IndexError: list index out of range Lines in the file look like following: word1 word2 word3 word4 yes word1 word2 word3 word4 no word1 word2 word3 word4 no word1 word2 word3 word4 no word1 word2 word3 word4 yes word1 word2 word3 word4 no word1 word2 word3 word4 yes word1 word2 word3 word4 no word1 word2 word3 word4 yes word1 word2 word3 word4 yes word1 word2 word3 word4 no word1 word2 word3 word4 no word1 word2 word3 word4 no word1 word2 word3 word4 yes word1 word2 word3 word4 no word1 word2 word3 word4 yes word1 word2 word3 word4 yes word1 word2 word3 word4 no word1 word2 word3 word4 no word1 word2 word3 word4 no word1 word2 word3 word4 no word1 word2 word3 word4 yes > What do we do at steps 4ff if the line does not end in "yes" or "no"? I forgot to mention that I know for sure that the file has ONLY lines that end in either "yes" or "no". Any suggestions are appreciated. Also, I feel that my code is not the best way of solving the problem even if the problem of list indices is solved. Is my guess right? Thank you! -dan On Sat, Apr 25, 2009 at 10:32 AM, bob gailer wrote: > Dan Liang wrote: > >> Dear Tutors, >> >> >> I have a file from which I want to extract lines that end in certain >> strings and print to a second file. More specifically, I want to: >> >> 1) iterate over each line in the file, and if it ends in "yes", print it. >> 2) move to the line following the one described in #1 above, and if it >> ends in, "no" print it. >> 3) move to third line, and if it ends in "no", print it. >> 4) move to fourth line, and if it ends in "no" discard it, but if it ends >> in "yes" repeat 1, 2, and 3 above. >> 5) move to fifth line, and if it ends in "no" discard it, but if it ends >> in "yes" repeat 1, 2, 3, and 4 above, and so on. >> >> The goal is to get a ratio of 1 to 2 "yes" to "no" lines from a file in >> such a way that keeps the order of the lines in output. An abstraction away >> from this so that any ratio of "yes" to "no" lines could be printed while >> keeping the order of the original lines would be great. >> > > Please show us what code you have written, and in what way it fails to meet > your expectations. > > Your specification is IMHO a nice piece of pseudocode which could translate > to Python fairly easily! > > What do we do at steps 4ff if the line does not end in "yes" or "no"? > > If you have not written any code make a stab at it. You could start by > asking "how in Python does one": > open a file? > iterate (loop)? > get the next line from a file? > test for equality? > examine the end of a string? > > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Working with lines from file and printing to another keeping sequential order
Hi Bob, Shantanoo, Kent, and tutors, Thank you Bob, Shantanoo, Kent for all the nice feedback. Exception handling, the concept of states in cs, and the use of the for loop with offset helped a lot. Here is the code I now have, based on your suggestions, and it does what I need: ListLines = [ line.rstrip() for line in open('test.txt') ] countYes = 0 countNo = 0 for i in range(len(ListLines)): if ListLines[i].endswith('yes'): countYes+=1 print "countYes", countYes, "\t\t", ListLines[i] if not ListLines[i].endswith('yes'): continue for offset in (1, 2, 3, 4, 5, 6, 7, 8): if i+offset < len(ListLines) and ListLines[i+offset].endswith('no'): countNo+=1 print "countNo", countNo, "\t\t", ListLines[i+offset] Thank you again! --dan On Sun, Apr 26, 2009 at 10:55 AM, Kent Johnson wrote: > On Sat, Apr 25, 2009 at 2:11 PM, Dan Liang wrote: > > Hi Bob and tutors, > > > > Thanks Bob for your response! currently I have the current code, but it > does > > not work: > > > > ListLines= [] > > for line in open('test.txt'): > > line = line.rstrip() > > ListLines.append(line) > > This could be written with a list comprehension: > ListLines = [ line.rstrip() for line in open('test.txt') ] > > > > > for i in range(len(ListLines)): > > > > if ListLines[i].endswith("yes") and ListLines[i+1].endswith("no") and > > ListLines[i+1].endswith("no"): > > print ListLines[i], ListLines[i+1], ListLines[i+2] > > elif ListLines[i].endswith("yes") and ListLines[i+1].endswith("no"): > > print ListLines[i], ListLines[i+1] > > elif ListLines[i].endswith("yes"): > > print ListLines[i] > > elif ListLines[i].endswith("no"): > > continue > > else: > > break > > You only need to test for ListLines[i].endswith('yes') once. Then you > could use a loop to test for lines ending with 'no'. > > for i in range(len(ListLines)): > if not ListLines[i].endswith('yes'): >continue > for offset in (1, 2): >if i+offset < len(ListLines) and ListLines[i+offset].endswith('no'): > print ListLines[i+offset] > > You could adapt the above for a variable number of 'no' lines with > something like > for offset in range(1, maxNo+1): > > > I get the following error: > > Traceback (most recent call last): > > File "test.py", line 18, in > > if ListLines[i].endswith("yes") and ListLines[i+1].endswith("no") and > > ListLines[i+1].endswith("no"): > > IndexError: list index out of range > > That is because you have a 'yes' line at the end of the file so the > check for 'no' tries to read past the end of ListLines. In my code the > test for i+offset < len(ListLines) will prevent that exception. > > Kent > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Iterating over a long list with regular expressions and changing each item?
Hi tutors, I am working on a file and need to replace each occurrence of a certain label (part of speech tag in this case) by a number of sub-labels. The file has the following format: word1 \tTag1 word2 \tTag2 word3 \tTag3 Now the tags are complex and I wanted to split them in a tab-delimited fashion to have this: word1 \t Tag1Part1 \t Tag2Part2 \t Tag3Part3 I searched online for some solution and found the code below which uses a dictionary to store the tags that I want to replace in keys and the sub-tags as values. The problem with this is that it sometimes replaces tags that are not surrounded by spaces, which I do not like to happen. Also, I wanted each new sub-tag to be followed by a tab, so that the new items that I end up having in my file are tab-delimited. For this, I put tabs between the items of each key in the dictionary. I started thinking that this will not be the best solution of the problem and perhaps a script that uses regular expressions would be better. Since I am new to Python, I thought I should ask you for your thoughts for a best solution. The items I want to replace are about 150 and I did not know how to iterate over them with regular expressions. Below is my previous code: #!usr/bin/python import re, sys f = file(sys.argv[1]) readed= f.read() def replace_words(text, word_dic): for k, v in word_dic.iteritems(): text = text.replace(k, v) return text # the dictionary has target_word:replacement_word pairs word_dic = { 'abbrev': 'abbrevnullnull', 'adj': 'adjnullnull', 'adv': 'advnullnull', 'case_def_acc': 'case_defaccnull', 'case_def_gen': 'case_defgennull', 'case_def_nom': 'case_defnomnull', 'case_indef_acc': 'case_indefaccnull', 'verb_part': 'verb_partnullnull'} # call the function and get the changed text myString = replace_words(readed, word_dic) fout = open(sys.argv[2], "w") fout.write(myString) fout.close() --dan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Iterating over a long list with regular expressions and changing each item?
Hi Spir and tutors, Thank you Spir for your response. I went ahead and tried your code after adding a couple of dictionary entries, as below: ---Code Begins--- #!usr/bin/python tags = { 'case_def_gen':['case_def','gen','null'], 'nsuff_fem_pl':['nsuff','null', 'null'], 'abbrev': ['abbrev, null, null'], 'adj': ['adj, null, null'], 'adv': ['adv, null, null'],} # tag dict TAB = '\t' def newlyTaggedWord(line): (word,tag) = line.split(TAB)# separate parts of line, keeping data only new_tags = tags['tag'] # read in dict--Index by string tagging = TAB.join(new_tags)# join with TABs return word + TAB + tagging # formatted result def replaceTagging(source_name, target_name): source_file = file(source_name, 'r') source = source_file.read() # not really necessary target_file = open(target_name, "w") # replacement loop for line in source: new_line = newlyTaggedWord(line) + '\n' target_file.write(new_line) source_file.close() target_file.close() if __name__ == "__main__": source_name = sys.argv[1] target_name = sys.argv[2] replaceTagging(source_name, target_name) ---Code Ends--- The file I am working on looks like this: word \t case_def_gen word \t nsuff_fem_pl word \t adj word \t abbrev word \t adv I get the following error when I try to run it, and I cannot figure out where the problem lies: ---Error Begins--- Traceback (most recent call last): File "tag.formatter.py", line 36, in ? replaceTagging(source_name, target_name) File "tag.formatter.py", line 28, in replaceTagging new_line = newlyTaggedWord(line) + '\n' File "tag.formatter.py", line 16, in newlyTaggedWord (word,tag) = line.split(TAB)# separate parts of line, keeping data only ValueError: unpack list of wrong size ---Error Ends--- Any ideas? Thank you! --dan From: Dan Liang Subject: [Tutor] Iterating over a long list with regular expressions and changing each item? To: tutor@python.org Message-ID: > > > Content-Type: text/plain; charset="iso-8859-1" > > Hi tutors, > > I am working on a file and need to replace each occurrence of a certain > label (part of speech tag in this case) by a number of sub-labels. The file > has the following format: > > word1 \tTag1 > word2 \tTag2 > word3 \tTag3 > > Now the tags are complex and I wanted to split them in a tab-delimited > fashion to have this: > > word1 \t Tag1Part1 \t Tag2Part2 \t Tag3Part3 > > I searched online for some solution and found the code below which uses a > dictionary to store the tags that I want to replace in keys and the > sub-tags > as values. The problem with this is that it sometimes replaces tags that > are > not surrounded by spaces, which I do not like to happen. Also, I wanted > each > new sub-tag to be followed by a tab, so that the new items that I end up > having in my file are tab-delimited. For this, I put tabs between the items > of each key in the dictionary. I started thinking that this will not be the > best solution of the problem and perhaps a script that uses regular > expressions would be better. Since I am new to Python, I thought I should > ask you for your thoughts for a best solution. The items I want to replace > are about 150 and I did not know how to iterate over them with regular > expressions. Below is my previous code: > > > #!usr/bin/python > > import re, sys > f = file(sys.argv[1]) > readed= f.read() > > def replace_words(text, word_dic): >for k, v in word_dic.iteritems(): >text = text.replace(k, v) >return text > > # the dictionary has target_word:replacement_word pairs > > word_dic = { > 'abbrev': 'abbrevnullnull', > 'adj': 'adjnullnull', > 'adv': 'advnullnull', > 'case_def_acc': 'case_defaccnull', > 'case_def_gen': 'case_defgennull', > 'case_def_nom': 'case_defnomnull', > 'case_indef_acc': 'case_indefaccnull', > 'verb_part': 'verb_partnullnull'} > > > # call the function and get the changed text > > myString = replace_words(readed, word_dic) > > > fout = open(sys.argv[2], "w") > fout.write(myString) > fout.close() > > --dan > -- next part -- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20090503/bd82a183/attachment-0001.htm > > > > -- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 63, Issue 8
Hello Spir, Alan, and Paul, Thank you for your help. I have been working on the file, but I still have a problem doing what I wanted. As a reminder, I have #!usr/bin/python tags = { 'noun-prop': 'noun_prop null null'.split(), 'case_def_gen': 'case_def gen null'.split(), 'dem_pron_f': 'dem_pron f null'.split(), 'case_def_acc': 'case_def acc null'.split(), } TAB = '\t' def newlyTaggedWord(line): (word,tag) = line.split(TAB)# separate parts of line, keeping data only new_tags = tags[tag] # read in dict tagging = TAB.join(new_tags)# join with TABs return word + TAB + tagging # formatted result def replaceTagging(source_name, target_name): target_file = open(target_name, "w") # replacement loop for line in open(source_name, "r"): new_line = newlyTaggedWord(line) + '\n' target_file.write(new_line) target_file.close() if __name__ == "__main__": source_name = sys.argv[1] target_name = sys.argv[2] replaceTagging(source_name, target_name) On Mon, May 4, 2009 at 12:38 PM, wrote: > Send Tutor mailing list submissions to >tutor@python.org > > To subscribe or unsubscribe via the World Wide Web, visit >http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to >tutor-requ...@python.org > > You can reach the person managing the list at >tutor-ow...@python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Iterating over a long list with regular expressions and > changing each item? (Paul McGuire) > 2. Advanced String Search using operators AND, OR etc.. (Alex Feddor) > 3. Re: Encode problem (Pablo P. F. de Faria) > 4. Re: Encode problem (Pablo P. F. de Faria) > 5. Re: Advanced String Search using operators AND, OR etc.. > (vince spicer) > > > -- > > Message: 1 > Date: Mon, 4 May 2009 11:17:53 -0500 > From: "Paul McGuire" > Subject: Re: [Tutor] Iterating over a long list with regular >expressions and changing each item? > To: > Message-ID: <99b447f3c7ef4996aa2ed683f1ee6...@awa2> > Content-Type: text/plain; charset="us-ascii" > > Original: > 'case_def_gen':['case_def','gen','null'], > 'nsuff_fem_pl':['nsuff','null', 'null'], > 'abbrev': ['abbrev, null, null'], > 'adj': ['adj, null, null'], > 'adv': ['adv, null, null'],} > > Note the values for 'abbrev', 'adj' and 'adv' are not lists, but strings > containing comma-separated lists. > > Should be: > 'case_def_gen':['case_def','gen','null'], > 'nsuff_fem_pl':['nsuff','null', 'null'], > 'abbrev': ['abbrev', 'null', 'null'], > 'adj': ['adj', 'null', 'null'], > 'adv': ['adv', 'null', 'null'],} > > For much of my own code, I find lists of string literals to be tedious to > enter, and easy to drop a ' character. This style is a little easier on > the > eyes, and harder to screw up. > > 'case_def_gen':['case_def gen null'.split()], > 'nsuff_fem_pl':['nsuff null null'.split()], > 'abbrev': ['abbrev null null'.split()], > 'adj': ['adj null null'.split()], > 'adv': ['adv null null'.split()],} > > Since all that your code does at runtime with the value strings is > "\t".join() them, then you might as well initialize the dict with these > computed values, for at least some small gain in runtime performance: > > T = lambda s : "\t".join(s.split()) > 'case_def_gen' : T('case_def gen null'), > 'nsuff_fem_pl' : T('nsuff null null'), > 'abbrev' : T('abbrev null null'), > 'adj' : T('adj null null'), > 'adv' : T('adv null null'),} > del T > > (Yes, I know PEP8 says *not* to add spaces to line up assignments or other > related values, but I think there are isolated cases where it does help to > see what's going on. You could even write this as: > > T = lambda s : "\t".join(s.split()) > 'case_def_gen' : T('case_def gen null'), > 'nsuff_fem_pl' : T('nsuff null null'), > 'abbrev' : T('abbrevnull null'), > 'adj' : T('adj null null'), > 'adv' : T('adv null null'),} > del T > > and the extra spaces help you to see the individual subtags more easily, > with no change in the resulting values since split() splits on multiple > whitespace the same as a single space.) > > Of course you could simply code as: > > 'case_def_gen' : T('case_def\tgen\t null'), > 'nsuff_fem_pl' : T('nsuff\tnull\tnull'), > 'abbrev' : T('abbrev\tnull\tnull'), > 'adj' : T('adj\tnull\tnull'), > 'adv' : T('adv\tnull\tnull'),} > > But I think readability definitely suffers here, I would probably go with > the penultimate version. > > -- Paul > > > > > -- > > Message: 2 > Date: Mon, 4 May 2009 14:45:06 +0200 > From: Alex Feddor > Subject: [Tutor] Advanced String Search using o
[Tutor] Replacing fields in lines of various lengths
(Please disregard my earlier message that was sent by mistake before I finished composing. Sorry about that! :(). Hello Spir, Alan, and Paul, and tutors, Thank you Spir, Alan, and Paul for your help with my previous code! Earlier, I was asking how to separate a composite tag like the one in field 2 below with sub-tags like those in the values of the dictionary below. In my original question, I was asking about data formatted as follows: w1\t case_def_acc w2\t noun_prop w3\t case_def_gen w4\t dem_pron_f And I put together the code below based on your suggestions, with minor changes and it does work. -Begin code #!usr/bin/python tags = { 'noun-prop': 'noun_prop null null'.split(), 'case_def_gen': 'case_def gen null'.split(), 'dem_pron_f': 'dem_pron f null'.split(), 'case_def_acc': 'case_def acc null'.split(), } TAB = '\t' def newlyTaggedWord(line): line = line.rstrip() # I strip line ending (word,tag) = line.split(TAB)# separate parts of line, keeping data only new_tags = tags[tag] # read in dict tagging = TAB.join(new_tags)# join with TABs return word + TAB + tagging # formatted result def replaceTagging(source_name, target_name): target_file = open(target_name, "w") # replacement loop for line in open(source_name, "r"): new_line = newlyTaggedWord(line) + '\n' target_file.write(new_line) source_name.close() target_file.close() if __name__ == "__main__": source_name = sys.argv[1] target_name = sys.argv[2] replaceTagging(source_name, target_name) -End code Now since I have to workon different data format as follows: -Begin data w1\t case_def_acc \t yes w2\t noun_prop \t no w3\t case_def_gen \t w4\t dem_pron_f \t no w3\t case_def_gen \t w4\t dem_pron_f \t no w1\t case_def_acc \t yes w3\t case_def_gen \t w3\t case_def_gen \t -End data Notices that some lines have nothing in yes-no filed, and hence end in a tab. My question is how to replace data in the filed of composite tags by sub-tags like those in the dictionary values above and still be able to print the whole line only with this change (i.e, composite tags replace by sub-tags). Earlier, we read words and tags from line directly into the dictionary since we were sure each line had 2 fields after separating by tabs. Here, lines have various field lengths and sometimes have yes and no finally, and sometimes not. I tried to make changes to the code above by changing the function where we read the dictionary, but it did not work. While it is ugly, I include it as a proof that I have worked on the problem. I am sure you will have various nice ideas. -End code def newlyTaggedWord(line): tagging = "" line = line.split(TAB)# separate parts of line, keeping data only if len(line)==3: word = line[-3] tag = line[-2] new_tags = tags[tag] decision = line[-1] # in decision I wanted to store #either yes or no if one of #these existed elif len(line)==2: word = line[-2] tag = line[-1] decision = TAB # I thought if it is a must to put sth in decision while decision #is really absent in line, I would put a tab. But I really want to #avoid putting anything there. new_tags = tags[tag] # read in dict tagging = TAB.join(new_tags)# join with TABs return word + TAB + tagging + TAB + decision -End code I appreciate your support! --dan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] FW: Kerberos Validation
Hi,I have Heimdal Kerberos server running under Solaris. It is working and my pam stack is correct as I can kinit on a client and validate on the unix command line. Under Linux (ubuntu 9.04 in this case) - I'd like to write a python program that will validate a user name and password against the kerberos server. I've found one module python-kerberos, but not a lot (any?) of examples. Does anyone on the list have any experience with kerberos validation that they can share? Thanks, Dan _ Windows Live: Keep your friends up to date with what you do online. http://windowslive.com/Campaign/SocialNetworking?ocid=PID23285::T:WLMTAGL:ON:WL:en-US:SI_SB_online:082009 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help deciding between python and ruby
> I think you will get at the least a slight bias toward Python. However, > I think you should do your own research and reach your own conclusions. > Simply to get you started I put the following into Google: 'Python or > Ruby: Which to learn' and got more than 1M hits. > Best of luck. > Robert Well, the slight (at the very least) bias toward Python is expected as this is a python mailing list. I have already done research on python and ruby via Google. I've found that python is described as more 'explicit,' used in multiple situations, has better libraries, and has unique 'spacing & underscore' syntax requirements; and ruby on the other is more 'implicit,' used more in web-apps (via ROR), emphasizes code-readability/beauty, and is more flexible (i.e. has more than one way of doing something). While the preceding information is nice, the information hasn't helped me decide which one to learn - that's the reason for my post. I want to sift through the hype for each language. I want to understand the perspectives of people who use python - why they like/dislike it, if/why the would recommend learning it, and what experiences they've had with python in professional contexts. To put my programming knowledge in context, I have experience with php and java; I enjoy php's ease and the syntax of java (everything is apparent from the code, although it can be a bit verbose). Look forward to the responses. Thanks. -Dan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can't figure out syntax error
Phew -- thanks, Ziyad. That did the trick all right. In my frustration to figure out the problem, I just began explicitly type-casting as many variables as I could, and missed the fact that I had done the same to this as well. Thanks again, Dan On 9-Jun-05, at 7:32 PM, ZIYAD A. M. AL-BATLY - [EMAIL PROTECTED] wrote: > On Thu, 2005-06-09 at 18:16 -0600, [EMAIL PROTECTED] > wrote: >> Hi there, >> >> I'm in the process of learning Python, and need some help deciphering >> the reason why the following code doesn't work: > >> int(num) = int(num) / 2 # this is integer division, so we >> truncate the decimal part > Here's your problem! "int(num)" will try to interpret "num" as an > integer and return that (if possible) as an "int" object, but you're > trying to assign it to the value of "int(num)/2" which doesn't make > sense! > > What you want, probably, is: > num = int(num) / 2 > > Here, "num" will be assigned the value (object actually) of the > resulting of "int(num)/2" which will be an object of type "int". > > Ziyad. > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to put an event into the Tcl/Tk event queue?
Hello Mr. Gauld, Your second guess about the scenario is right: I want to automate tests of Tcl/Tk GUIs. I know about the GUI test automation tools like WATSUP, PyWinAuto, winGuiAuto etc., and will use one if necessary. But test automation is usually easier at the lowest possible level for the test target (as per your suggestion to test the back-end functions directly). In this case, my test target is the Tcl/Tk GUI itself. The Tcl/Tk functions I mentioned (Tcl_QueueEvent etc.) are listed in my copy of the Tcl/Tk Man pages (downloadable from www.tcl.tk/man). I believe they are C or C++ functions. Thanks for the explanation of what Tkinter does and doesn't cover. Is there another Python module that does include Python wrappers for Tcl/Tk C functions? My first glance at send() and event_generate() gave me the idea they were for other purposes. Your suggestion triggered a second glance; maybe event_generate can do what I need. I'll study it some more. Thanks for the clues - Dan K. "Alan Gauld" <[EMAIL PROTECTED]> wrote: > > I'd like to simulate user input to TkInter applications from > > another Python script, by inserting events in the Tcl event queue. > > There are two scenarios where I'd expect that to be needed: > 1) To roboticise an existing app, particularly if you don;t have > source code access. > 2) testing a GUI. > > Other than that it's usually easier to go in at the level below the > GUI and > call the underlying commands directly. Is that a possibility here? > > > Tcl/Tk has a couple functions for this (Tk_QueueWindowEvent > > and Tcl_QueueEvent). > > These were new to me and indeed don't appear in either of > my Tcl refrence books (Ousterhout and O'Reilly Nutshell) > Are they recent additions? > > > Is there a Python interface for either of those? I can't find > > any... > > Neither can I. > > > My second choice would be to use Tcl_CreateEventSource, > > but I don't see a Python interface for that, either. > > Nope, me neither. No references in my books and no > Python/Tkinter equivalents. In fact my Tcl prompt doesn't > recognise any of the 3 commands you cite. Are these > actuially Tcl/Tk interpreter commands or C interface > functions? Only interpreter commands are reproduced > in Tkinter. > > > I'd rather not work through the actual GUI interface if I can avoid > > it. > > Why do you need to work through the GUI events? > Normally the GUI is there to connect humans to the back end code. > If an app needs access to the back end code it can usually call the > functions directly using more conventional IPC mechanisms. > > There are a couple of higher level methods that might be of use? > > send(app, cmd, *args) > > event_generate(sequence, option=...) > > Dunno if they will help. > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] script ?
How can I have this script exucute a .exe file instead of beeping the system speaker? __ import os import time z = 2 while z ==2: connected = False while not connected: o=os.popen("netstat -an") for l in o: try: if l.split()[1].endswith("159.215.49.8.116:5"): print "\a\a\a\a\aMatch!" connected = True else: print "Nothing" except IndexError: print "Index Exception" time.sleep(1) amount=0 while connected: o=os.popen("netstat -an") for l in o: try: if l.split()[1].endswith("159.215.49.8:5"): print "Still There" connected = True amount +=1 print amount else: print "Nothing" except IndexError: print "Index Exception" time.sleep(1) if amount == 1: amount -=1 else: print "It's Gone" connected = False print "\a\a" raw_input("Press Enter to close") ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] help
i am making a simple script to get the hang of Tkinter. i want to use the input of the user from a Entry and calcuate the area. i have tryied many way... as you can see in my script. the Entry is under def area(): and the output i want is under def cal(): ... please help me fix my code and explain to me what you did.. thanks in advance. [EMAIL PROTECTED] #program made and maintained by Dan Deternova #start of program from Tkinter import * # tells computer we are using Tkinter modual from tkMessageBox import * def cal(): win4 = Toplevel print 'area = ', 'w'*'h' def notyet(): showerror('not yet avalable') win = Tk() # makes windows and has value for Tk def makemenu(Tk): top = Menu(win) win.config(menu=top) file = Menu(top) file.add_command(label='save your name', command=newwin, underline=0) file.add_command(label='quit', command=win.destroy, underline=0) file.add_command(label='quit all', command=win.quit, underline=0) top.add_cascade(label='file', menu=file, underline=0) edit = Menu(top, tearoff=0) edit.add_command(label='copy', command=notyet, underline=0) edit.add_command(label='paste', command=notyet, underline=0) edit.add_command(label='quit', command=win.destroy, underline=0) top.add_cascade(label='edit', menu=edit, underline=0) def newwin(): # callback to define button newwin. win2 = Toplevel() # makes new window when button is pressed. named win2 widget = Label(win2, text='your name here').pack() # line 'type your name here' is printed on top of entry name = StringVar() widget = Entry(win2, textvariable=name).pack() # makes entry in new window at the top. widget = Label(win2, text='age here').pack() # prints the line 'age here' age = StringVar() widget = Entry(win2, textvariable=age).pack() # makes entry widget = Label(win2, text='type your address here').pack() address = StringVar() widget = Entry(win2, textvariable=address).pack() def save(): f=file('fname','a') f.write(name.get()+'\n') f.write(age.get()+'\n') f.write(address.get()+'\n') widget = Button(win2, text='save', command=save).pack(side=LEFT) widget = Button(win2, text='quit', command=win2.destroy).pack(side=RIGHT) def area(): win3 = Toplevel() widget = Label(win3, text='type hieght here: ').pack() h = StringVar() widget = Entry(win3, textvariable=h).pack() widget = Label(win3, text='type width here: ').pack() w = StringVar() widget = Entry(win3, textvariable=w).pack() widget = Button(win3, text=' calculate ', command=cal).pack(side=BOTTOM, expand=YES, fill=BOTH) fontentry = ('times', 20, 'bold') # (font, size, style) defonision for fontentry. will be used later on in the program widget = Entry(win, text='type here') # makes entry point in 'win' makemenu(win) widget.config(font=fontentry) # makes the font of entry equal to 'fontentry' widget.config(bg='black', fg='yellow') # makes the background (bg) black and the forground (text) yellow widget.pack(side=TOP, expand=YES, fill=BOTH) # 'packs' the entry on top of win and expands and fill the Y axes widget = Button(win, text="your name", command=newwin).pack(side=LEFT, expand=YES, fill=BOTH)# creates button that says 'your name'. see newwin callback for output. widget = Button(win, text='quit all', command=win.quit).pack(side=BOTTOM, expand=YES, fill=BOTH) widget = Button(win, text='quit', command=win.destroy).pack(side=RIGHT, expand=YES, fill=BOTH) widget = Button(win, text='area', command=area).pack(side=LEFT, expand=YES, fill=BOTH) win.title('my program') #end of program ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] help
ok. i know python and want to turn all my programs i made when i was learning python into Tkinter programs. i dont know how to make if satments and display the output like this in python: if cmd == quit: print "press exit to quit" i have no idea how to do that in Tkinter please help. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] file opening and errors.
Hi, I usually use perl but fancy a bit of a change so have started playing with python. using perl to open a file or directory I usually use: open(FILE, $file) or die "Error: $!\n"; The $! is a perl variable that holds an error should the open fail, example being : "No such file or directory". With python I have use a try except block but I have no idea how I would get the same warning from python as I would from perl (the reason for the exception), I am not even sure if this is possible (I assume it must be) as google searching has been fruitless. Thanks for any help, pointers and suggestions. Dan. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] perldoc - confused!
Hello Python List, When using perl I tend to use perldoc. I spent ages today trying to list all items in a directory, simple I now know (os.listdir) but I was trying to use os.walk simply because I had no idea that listdir existed. I only found listdir because I was reading about walk Is there a python version of perldoc? Thanks for any guidance Dan. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [OT] triangulation
Hello, On Thu, 2005-11-10 at 11:00 +0100, Joerg Woelke wrote: > On Thu, Nov 10, 2005 at 02:04:20PM +1300, John Fouhy wrote: > > On 10/11/05, Gregor Lingl <[EMAIL PROTECTED]> wrote: > > > but Shi Mu didn't ask for a program in English ;-) > > > > This is pretty off-topic, but --- > > > > Is it possible to be a programmer and not speak English? Are there any > > languages out there where the reserved words, library functions, etc. > > are in (say) German? I was bored: http://en.wikipedia.org/wiki/Category:Non-English- based_programming_languages Enjoy. Dan. > > Dont know for sure, but perhaps Plankalkül by Konrad Zuse? > > > -- > > John. > -- Daniel Klose PhD Student - Taylor Group Mathematical Biology National Institute for Medical Research The Ridgeway Mill Hill London NW7 1AA ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python-ldap
On Nov 22, 2005, at 2:08 PM, Pat Martin wrote: > I am new to python and fairly new to programming. I have written some > ldap scripts in perl and am trying to learn how to do that in > python. I > found some code on the net using the python-ldap module (the unaltered > code is at the bottom of this email) and have adapted it to my needs, > the code works fine. I want to learn what some of the things in the > code > are. The two things I don't understand are > ldap.SCOPE_SUBTREE and > ldap.RES_SEARCH_ENTRY > when I print those out I get integers 2 and 100 respectively, I am not > sure if they change but that is what they start out at. I am figuring > other modules use similar things (variables?), can someone point me to > where I can understand what more about what these are. SCOPE_SUBTREE is one of three possible scopes you can use. Remember that LDAP is a tree-based heirarchy (arranged much like the old Windows Explorer file tree view). So that tree is divided into branches, sub branches, etc. How you limit your search depends on two things: 1. The starting branch point (the base) 2. The scope (which is applied to the base). So say you have ou=foo,ou=bar,o=root. There are three bases you could choose to start from. o=root ou=bar,o=root ou=foo,ou=bar,o=root If you used base o=root with a scope of SCOPE_BASE, the only possible entry that could be returned is o=root itself. SCOPE_BASE indicates that the scope of the search should be limited to the base itself - not to any of its sub branches or sub entries. Just itself. If you used base o=root with a scope of SCOPE_ONE, you would be able to obtain entries like this: ou=bar,o=root cn=something,o=root cn=another,o=root cn=third,o=root In other words, given a base, you can get entries one level below; the entries immediately subordinate to your base (but not the base itself). You could not get back ou=foo,ou=bar,o=root because that is not immediately beneath o=root. If you used base o=root with a scope of SCOPE_SUBTREE, you would be able to obtain any entry anywhere in the tree, including the base. This translates to: start the base, anything further down the line is okay. Therefore, if you used a base of ou=bar,o=root, you could get these entries: ou=bar,o=root cn=something,ou=bar,o=root cn=something-else,ou=foo,ou=bar,o=root But you could not get: o=root Because that is outside the scope (at a higher level than the base). Behind the scenes, the scopes have different numbers, which is why you get the integer value when you printed SCOPE_SUBTREE. These numbers don't really matter; they're just values used by the libraries. Just ignore them and use the constants SCOPE_BASE, SCOPE_ONE, SCOPE_SUBTREE. Unless you have a specific reason to use another scope, subtree is usually the default choice. I've had plenty of occasion to use the other two scopes, though. RES_SEARCH_ENTRY is, as far as I know, just a way to test if something is an LDAP entry object. So if you are iterating through a set of results, you can say if result_type == ldap.RES_SEARCH_ENTRY: result_set.append(result_data) Which means, append the entry to the result set only if it actually is an entry object. More information here: http://python-ldap.sourceforge.net/doc/python-ldap/ldap-objects.html -dan -- Television is one of the Six Fundamental Forces of the Universe; with the other five being Gravity, Duct Tape, Whining, Remote Control, and the Force That Pulls Dogs Toward the Groins of Stranges. -Dave Barry ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] my text adventure
On Dec 3, 2005, at 9:40 PM, david wrote: sorry i forgot a subject line. i have looked at the pickle module and was able to pickle world. but i can't figure how to restore everything.import pickledef save_game(state, filename): file = open(filename, 'w') pickle.dump(state, file) file.close()def load_game(filename): file = open(filename, 'r') state = pickle.load(file) file.close() return statesave_game(world, 'mygame')world = load_game('mygame')-- logic (n.): the art of being wrong with confidence. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How do I fix this Invalid Mode?
On Dec 17, 2005, at 2:00 PM, Nathan Pinno wrote: Here is the latest error: The Currency Exchange ProgramBy Nathan Pinno Traceback (most recent call last): File "D:\Python24\exchange.py", line 27, in -toplevel- store = open('exch.txt', 'b')#loadIOError: invalid mode: b[snip...] store = open('exch.txt', 'b')#loadexch = pickle.load(store)store.close()It looks like what you are trying to do is read exch.txt as a binary file. The problem is that 'b' by itself is not a valid mode; it's a modifier to one of the other modes (r, w or a).So to read a file in binary mode, what you want to do is: store = open('exch.txt', 'rb')Using your own code as an example, see how you implemented the save feature (option 9). That open() correctly uses the 'wb' flag to write the file in binary mode. elif menu_option == 9: store = open("exch.txt", 'wb') #save pickle.dump(exch, store) store.close() break -dan-- Black holes are where God divided by zero. -Steven Wright ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] issuing system commands
Hi All, I am trying to break my nasty habit of doing EVERYTHING in perl and for this task I figure python is one of the better options. I would like to do several things: 1. take user input - this will be a password 2. use some sort of function that converts the unser input to * or the typical '' no output of linux. 3. Take this input and use it in the os.system to issue an su command. All I have so far is: import os, sys password = raw_input('Enter USER password: ') print "you entered ", password os.system("su perlmunky password") I guess point three is more of a system dependent problem - As I work on a mac and linux is there a better way of issuing these commands? All I really want to do is mount/unmount directories and shift / delete files. I know how to do this in perl, but as I said I really want to kick the habit. Any help - pointers - advice would be most welcome. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running an exe from Python
On 2/26/07, Nagendra Singh <[EMAIL PROTECTED]> wrote: Thanks a lot for all the suggestions. I used the function subprocess.call( 'c:\abc.exe c:\data\file1'), but as before the command window opens and closes very fast a value of 1 is displayed. How do I see the results?? I am sorry if I sound dumb. Singh On 2/23/07, Alan Gauld <[EMAIL PROTECTED]> wrote: > > > "Rikard Bosnjakovic" <[EMAIL PROTECTED]> wrote > > >> How can I get python to display > >> the results in the interactive window or what is the right way to > >> do this. > > > > Use os.popen: > > As Rikard, Richard and Hugo have pointed out there are > numerous ways to do this in Python. > > The officially sanctioned way nowadays is to use the subprocess > module. It supercedes all tthe previous methods being both more > powerful, more flexible and fairly easy to use. > > All the techniques are discussed in my Using the OS topic in > my tutorial. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor I am not a big user of python, hence the username, however I used the os.popen command as suggested by Rikard In the shell: data = os.popen('ls') type(data) Then a loop over the data object for f in data: print f seemed to do the job. I did notice that I could not capture the information to a var using the subprocess call - I HAVE NOT READ THE DOCs (yet) - a quick look suggested that this *should* work The call I made using subprocess from subprocess import call foo = call("ls") ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] R: Tutor Digest, Vol 125, Issue 49
DISCLAIMER* I have deliberately not read any of the other replies to this problem so my answer may be totally redundant! (but here it is anyway...) One of the first issues that had to be addressed is the fact that your "CSV" file is probably not in the format you assume it is. Every line is a list, not the traditional "string separated by commas" format that one normally expects in a CSV file. One way to deal with that is to resave the file as a .txt file and deal with each line as one would normally do with a list, i.e. use list subscripting to manipulate each list element with regex code. Having said that, in the spirit of minimalism, there are ways to deal with it as a CSV file as well. First, import the csv module and use the reader() method to properly access the contents. importre importcsv withopen(/'non.csv'/, /'r'/) asp: f = csv.reader(p, delimiter = /','/) Then use a for loop to access each line and put the regex statements in the print statement forw inf: print(re.sub(r/'(\.\d)'/,/''/,w[0]), re.sub(r/'(\.\d)'/,/''/, w[1])) The regex statements access the list elements with subscripting. The "$" was not necessary and without it you get the desired results. TO SUMMARIZE: With the following contents of file named "non.csv": ['uc002uvo.3 ', 'uc001mae.1'] ['uc010dya.2 ', 'uc001kko.2'] and the following code run in Eclipse: ##test.py importre importcsv withopen(/'non.csv'/, /'r'/) asp: f = csv.reader(p, delimiter = /','/) forw inf: print(re.sub(r/'(\.\d)'/,/''/,w[0]), re.sub(r/'(\.\d)'/,/''/, w[1])) I get: ['uc002uvo ''uc001mae'] ['uc010dya ''uc001kko'] On 7/16/14, 4:04 AM, jarod...@libero.it wrote: Hi there!!! I have a file with this data ['uc002uvo.3 ', 'uc001mae.1'] ['uc010dya.2 ', 'uc001kko.2'] ['uc003ejx.2 ', 'uc010yfr.1'] ['uc001bhk.2 ', 'uc003eib.2'] ['uc001znc.2 ', 'uc001efn.2'] ['uc002ycq.2 ', 'uc001vnh.2'] ['uc001odf.1 ', 'uc002mwd.2'] ['uc010jkn.1 ', 'uc010luk.1'] ['uc003uhf.3 ', 'uc010tqd.1'] ['uc002rue.3 ', 'uc001tex.2'] ['uc011dtt.1 ', 'uc001lkv.1'] ['uc003yyt.2 ', 'uc003mkl.2'] ['uc003pkv.2 ', 'uc003ytw.2'] ['uc010bhz.2 ', 'uc002kbt.1'] ['uc001wnj.2 ', 'uc009wtj.1'] ['uc011lyh.1 ', 'uc003jvb.2'] ['uc002awj.1 ', 'uc009znm.1'] ['uc010bft.2 ', 'uc002cxz.1'] ['uc011mar.1 ', 'uc001lvb.1'] ['uc001oxl.2 ', 'uc002lvx.1'] I want to replace of the things after the dots, so I want to have a file with this output: ['uc002uvo ', 'uc001mae'] ['uc010dya ', 'uc001kko'] ... I try to use regular expression but I have a strange output with open("non_annotati.csv") as p: for i in p: lines= i.rstrip("\n").split("\t") mit = re.sub(r'(\.\d$)','',lines[0]) mit2 = re.sub(r'(\.\d$)','',lines[1]) print mit,mit2 uc003klv.2 uc010lxj uc001tzy.2 uc011kzk uc010qdj.1 uc001iku uc004coe.2 uc002vmf uc002dvw.2 uc004bxn uc001dmp.2 uc001dmo uc002rqd.2 uc010ynl uc010cvm.1 uc002qjc uc003ewy.3 uc003hgx uc002ejy.2 uc003mvb uc002fou.1 uc010ilx uc003vhf.2 uc010qlo uc003mix.2 uc010tdt uc002nez.1 uc003wxe uc011cpu.1 uc002keg uc001ovu.2 uc011dne uc010zfg.1 uc001jvq uc010jlf.2 uc011azi uc001ors.3 uc001vzx uc010tyt.1 uc003vih uc010fde.2 uc002xgq uc010bit.1 uc003zle uc010xcb.1 uc010wsg uc011acg.1 uc009wlp uc002bnj.2 uc004ckd Where is the error? what is wrong in my regular expression code? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] SOAPpy and ZSI
Hi, I've been tasked with setting up a basic SOAP client and I'm its been the most frustrating python experience. Here's the code: from LoginService_services import * import sys from SOAPpy import SOAPProxy # get a port proxy instance loc = LoginServiceLocator() port = loc.getLogin(in0='pbs_uen', in1='TDapi', in2='3dcarapi') # create a new request req = LoginRequest() # call the remote method resp = port.Login(req) lr = resp.LoginReturn lri0 = lr.get_element_items()[0] service_url = lri0.Value n = 'http://DefaultNamespace' server = SOAPProxy(service_url, namespace=n) server.config.dumpSOAPOut = 1 server.config.dumpSOAPIn = 1 server.config.dumpHeadersOut = 1 server.config.dumpHeadersIn = 1 test = server.greeting() Notice I use ZSI (LoginService_services) for the Login and then SOAPpy for the post log-in stuff (ZSI's wsdl2py script broke on the post log-in WSDL). The login part works fine. It returns a URL with a session id appended. server.greeting() creates this envelope which I can see because of the dumps: http://schemas.xmlsoap.org/soap/encoding/"; xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"; xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"; > http://DefaultNamespace"; SOAP-ENC:root="1"> but then this error follows right after: File "generic_usage.py", line 34, in test = server.greeting() File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/SOAPpy/Client.py", line 470, in __call__ return self.__r_call(*args, **kw) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/SOAPpy/Client.py", line 492, in __r_call self.__hd, self.__ma) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/SOAPpy/Client.py", line 363, in __call config = self.config) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/SOAPpy/Client.py", line 252, in call raise HTTPError(code, msg) SOAPpy.Errors.HTTPError: line 252 of Client.py is: if code == 500 and not \ ( startswith(content_type, "text/xml") and message_len > 0 ): raise HTTPError(code, msg) I can't tell if the server is returning the 500 error or if the transport is. I honestly don't know where to go from here. I wouldn't doubt that the envelope isn't correct for the service but I don't have access to any more info on that. Help much appreciated. Dan "All men dream: but not equally. Those who dream by night in the dusty recesses of their minds wake in the day to find that it was vanity: but the dreamers of the day are dangerous men, for they may act their dreams with open eyes, to make it possible." -T. E. Lawrence - ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor