looping list problem
HI all, I'm fairly new to python and programming in general so I was hoping someone here may be able to help me. Let me explain what the problem I'm having is: I am trying to parse the XML of an attributes object I created, this object has the structure outlined below. Everything is ok on the parsing front until I try to get the values in ucl_navhide (StringField); these are basically the id's of objects I wish to hide in a website navigation menu separated by a space: root atts tb-black UCL Web Services section_header_white section_subheader_white cms-assets/images/ucl0001 ucl0001 normal yes 3_columns test1 test2 I have a script 'normalmenu' that I will eventually be using to generate a navigation menu for a website here it is in its present development state: attobject = context.get_attobject() navstring = context.get_uclattribute(attobject, 'ucl_navhide') hiddennavelements = navstring.split(' ') for hiddennavelement in hiddennavelements: return hiddennavelement So the script 'get_attobject' basically looks for an instance of the attributes object in the current folder, if it doesn't locate one then it uses acquisition to find one in a parent folder. The script 'get_uclattribute' then gets the nodeValues of the requested node. In this instance its ucl_navhide, then I split the 'navstring' string at the spaces and attempt the for-loop to output each of the values. Unfortunately it appears I am unable to loop through each of the list items in hiddennavelements, as it only returns the first value & will not repeat. Strangely if I test to output the value of hiddennavelements it looks like this: [u'test1', u'test2'] which I believe the u refers to Unicode, although I could be wrong. Even more bizarrely if I test the len(hiddennavelements) it returns the correct result (2), so why wont my for-loop work? Hope someone can help, or point out my schoolboy error. Jon -- http://mail.python.org/mailman/listinfo/python-list
RE: looping list problem
Ok so I changed it to this: attobject = context.get_attobject() navstring = context.get_uclattribute(attobject, 'ucl_navhide') hiddennavelements = navstring.split(' ') for hiddennavelement in hiddennavelements: yield hiddennavelements But I get the following error- Line 5: Yield statements are not allowed. Any ideas -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Fredrik Lundh Sent: 16 August 2005 13:44 To: python-list@python.org Subject: Re: looping list problem Jon Bowlas wrote: > attobject = context.get_attobject() > navstring = context.get_uclattribute(attobject, 'ucl_navhide') > hiddennavelements = navstring.split(' ') > for hiddennavelement in hiddennavelements: >return hiddennavelement > > So the script 'get_attobject' basically looks for an instance of the > attributes object in the current folder, if it doesn't locate one then it > uses acquisition to find one in a parent folder. The script > 'get_uclattribute' then gets the nodeValues of the requested node. In this > instance its ucl_navhide, then I split the 'navstring' string at the spaces > and attempt the for-loop to output each of the values. > > Unfortunately it appears I am unable to loop through each of the list items > in hiddennavelements, as it only returns the first value & will not repeat. did you perhaps mean to use "yield" instead of "return" ? -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: looping list problem
Ok, so I've adapted my script calling it a hiddens() function and included it inside my get_tree_html function which creates my navigation: pub = context.get_publication() obj = context.aq_inner fpath = context.getPhysicalPath() def hiddens(): attobject = context.get_attobject() navstring = context.get_uclattribute(attobject, 'ucl_navhide') return navstring.split(' ') def get_tree_html(node, endobj): tree = '' endpath = endobj.getPhysicalPath() for c in node.get_ordered_publishables(): if not c.is_published(): continue bert=c.getId(); if bert=="index_right": continue if bert=="images": continue # this is where I loop through he elements returned by my hiddens function, comparing them with the value of bert for element in hiddens(): if element==bert: continue ppath = c.aq_parent.getPhysicalPath() if not fpath[:len(ppath)] == ppath: continue if len(ppath) - 1 > len(endpath): continue html_si = '\n%(title)s' cl = 'space' if c == endobj: cl = 'space' si = {'url': c.absolute_url(), 'class': cl, 'title': c.getProperty('short_title') or c.get_title()} tree += html_si % si if (c.get_container() == c and c.is_transparent()): tree += get_tree_html(c, endobj) tree += '\n' if tree: tree = ' %s \n' %tree return tree top_class = 'space' if pub.aq_inner == obj: top_class = 'space' treetop = '\n\n' return '%s%s' % (treetop, get_tree_html(pub, obj)[19:]) I was hoping that this would loop through the elements in the list returned by the hiddens function comparing them with the id of the current value of c (bert) and if they are the same then it should ignore it and move onto the next one, but it doesn't seem to do anything. Any help would be appreciated. Incidentally I'm doing this in zope. Jon -----Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Peter Otten Sent: 16 August 2005 14:41 To: python-list@python.org Subject: RE: looping list problem Jon Bowlas wrote: > Ok so I changed it to this: > > attobject = context.get_attobject() > navstring = context.get_uclattribute(attobject, 'ucl_navhide') > hiddennavelements = navstring.split(' ') > for hiddennavelement in hiddennavelements: > yield hiddennavelements > > But I get the following error- Line 5: Yield statements are not allowed. Please show us some more code -- especially the function containing and the function calling the above chunk. Generally speaking, a function terminates when execution reaches the first return statement, e. g. def f(): for i in 1, 2, 3: return i will always return 1. A generator, on the other hand, def g(): for i in 1, 2, 3: yield i will yield 1, 2, and 3, but the calling code then needs itself a for loop: for i in g(): # do something with i My guess would be that you should either modify your for loop to > attobject = context.get_attobject() > navstring = context.get_uclattribute(attobject, 'ucl_navhide') > hiddennavelements = navstring.split(' ') for hiddennavelement in hiddennavelements: # do something with hiddennavelement or just return all elements at once def some_func(): # ... attobject = context.get_attobject() navstring = context.get_uclattribute(attobject, 'ucl_navhide') return navstring.split(' ') and then operate on the items in the hiddennavelements list in the calling code: for element in some_func(): # do something with element Peter -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: looping list problem
Many thanks for your help, worked a treat Jon -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Peter Otten Sent: 16 August 2005 17:25 To: python-list@python.org Subject: RE: looping list problem Jon Bowlas wrote: > Incidentally I'm doing this in zope. Many posters (including me) in this newsgroup don't do zope, so your best option is to ask on a zope-related mailing list. > I was hoping that this would loop through the elements in the list > returned by the hiddens function comparing them with the id of the current > value of c (bert) and if they are the same then it should ignore it and > move onto the next one, but it doesn't seem to do anything. > Ok, so I've adapted my script calling it a hiddens() function and included > it inside my get_tree_html function which creates my navigation: > > pub = context.get_publication() > obj = context.aq_inner > fpath = context.getPhysicalPath() > > def hiddens(): > attobject = context.get_attobject() > navstring = context.get_uclattribute(attobject, 'ucl_navhide') > return navstring.split(' ') > > def get_tree_html(node, endobj): > tree = '' > endpath = endobj.getPhysicalPath() > for c in node.get_ordered_publishables(): > if not c.is_published(): > continue > bert=c.getId(); > if bert=="index_right": > continue > if bert=="images": > continue > # this is where I loop through he elements returned by my hiddens > # function, comparing them with the value of bert Replace these lines > for element in hiddens(): > if element==bert: > continue # with the next hidden element with if bert in hiddens(): continue # with the next publishable c A 'continue' statement only affects the innermost loop, and as you don't have any code that follows it in the for-element-loop it didn't have any effect. Peter -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
coercing to Unicode: need string or buffer, NoneType found
Hi listers, I wrote this script in Zope some time ago and it worked for a while, but now I'm getting the following error: TypeError: coercing to Unicode: need string or buffer, NoneType found Here's my script: results = context.module_retriever().tuples() # call to ZSQLMethod converted = [] for result in results: result = list(result) # make a list from the tuple for i in range(len(result)): # for each element in the listified tuple, make decode to a # unicode from the latin-1 string result[i] = unicode(result[i], 'latin-1') converted.append(tuple(result)) # tuplify again return converted Where module_retriever is a simple Z SQL method that returns a module title and a module code. So results = context.module_retriever().tuples() returns: [('Developmental Neurobiology', 'ANAT2008'), ('Neuroanatomy', 'ANAT2009'),('etc...', 'etc..'),..]So I was hoping someone might be able to identify what I've done wrong here. It is a little mistifying as to why it's suddenly stopped working though.CheersJon -- http://mail.python.org/mailman/listinfo/python-list
Re: coercing to Unicode: need string or buffer, NoneType found
Ahh, that did it, thanks very much. Jon - Original Message - From: <[EMAIL PROTECTED]> Newsgroups: comp.lang.python To: Sent: Thursday, July 27, 2006 11:19 AM Subject: Re: coercing to Unicode: need string or buffer, NoneType found > > Jon Bowlas wrote: > >> Here's my script: >> >> results = context.module_retriever().tuples() # call to ZSQLMethod >> converted = [] >> for result in results: >>result = list(result) # make a list from the tuple >>for i in range(len(result)): >> # for each element in the listified tuple, make decode to a >> # unicode from the latin-1 string > > try this: > if result[i] is None: continue > >> result[i] = unicode(result[i], 'latin-1') >>converted.append(tuple(result)) # tuplify again >> return converted > > regards, > Rob > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: coercing to Unicode: need string or buffer, NoneType found
Ahh yes there are a couple of dodgy records that seem to have been added. many thanks. Jon - Original Message - From: "Peter Otten" <[EMAIL PROTECTED]> Newsgroups: comp.lang.python To: Sent: Thursday, July 27, 2006 11:22 AM Subject: Re: coercing to Unicode: need string or buffer, NoneType found > Jon Bowlas wrote: > >> I wrote this script in Zope some time ago and it worked for a while, but >> now I'm getting the following error: >> TypeError: coercing to Unicode: need string or buffer, NoneType found >> >> Here's my script: >> >> results = context.module_retriever().tuples() # call to ZSQLMethod >> converted = [] >> for result in results: >>result = list(result) # make a list from the tuple >>for i in range(len(result)): >> # for each element in the listified tuple, make decode to a >> # unicode from the latin-1 string >> result[i] = unicode(result[i], 'latin-1') >>converted.append(tuple(result)) # tuplify again >> return converted >> >> Where module_retriever is a simple Z SQL method that returns a module >> title and a module code. >> So results = context.module_retriever().tuples() returns: >> [('Developmental Neurobiology', 'ANAT2008'), ('Neuroanatomy', >> 'ANAT2009'),('etc...', 'etc..'),..]So I was hoping someone might be able >> to identify what I've done wrong here. It is a little mistifying as to >> why >> it's suddenly stopped working though.CheersJon > > This may be an indication that in your database you have a record with a > None value, e. g. > >[('Developmental Neurobiology', 'ANAT2008'), > ('Neuroanatomy', 'ANAT2009'), > ('Man in black', None)]) > > and most likely the right fix is to correct the database entry and make > sure > that no new such records can be entered into it. > > If that is not possible, a quick fix would be to replace your unicode() > call > with something that special-cases None: > > def from_latin(s): >if s is None: >return None # or maybe 'return u""', if your app expects a unicode ># string >return unicode(s, "latin-1") > > By the way, in recent Python your snippet might become > >converted = [] >for record in results: ># prior to 2.4: tuple([...]) >converted.append(tuple(from_latin(field) for field in record)) >return converted > > Peter > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: coercing to Unicode: need string or buffer, NoneType found
It says line 8 in the traceback so I guess its result[i] = unicode(result[i], 'latin-1') Jon - Original Message - From: "Sybren Stuvel" <[EMAIL PROTECTED]> Newsgroups: comp.lang.python To: Sent: Thursday, July 27, 2006 11:06 AM Subject: Re: coercing to Unicode: need string or buffer, NoneType found > Jon Bowlas enlightened us with: >> I wrote this script in Zope some time ago and it worked for a while, >> but now I'm getting the following error: >> TypeError: coercing to Unicode: need string or buffer, NoneType >> found > > What line is causing the error? > > Sybren > -- > The problem with the world is stupidity. Not saying there should be a > capital punishment for stupidity, but why don't we just take the > safety labels off of everything and let the problem solve itself? > Frank Zappa > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
ftplib returns EOFError
Hi All, I've written a little method to connect to an ftpserver which works well, however when I send a file using this ftp connection oddly I _sometimes_ get returned an EOFError from ftplib.getline even though my file is actually transferred. Here's my script: def uploadViaFtp(self, file, filename): '''A method to upload a file via ftp''' ftpserverloc = self.getItunesUftpServer() ftpserverusername = self.getItunesUftpUser() ftpserverpassword = self.getItunesUftpPsswd() ftp = ftplib.FTP(ftpserverloc) ftp.login(ftpserverusername, ftpserverpassword) try: ftp.storbinary("STOR " + filename, file, 1024) finally: file.close() ftp.quit() And here's the traceback: Traceback (innermost last): Module ZPublisher.Publish, line 114, in publish Module ZPublisher.mapply, line 88, in mapply Module ZPublisher.Publish, line 40, in call_object Module Products.FileSystemSite.FSPythonScript, line 108, in __call__ Module Shared.DC.Scripts.Bindings, line 311, in __call__ Module Shared.DC.Scripts.Bindings, line 348, in _bindAndExec Module Products.FileSystemSite.FSPythonScript, line 164, in _exec Module None, line 28, in upload_submit - - Line 28 Module Products.UCLItunesUPodcast.UCLItunesUService, line 138, in uploadViaFtp Module ftplib, line 523, in quit Module ftplib, line 246, in voidcmd Module ftplib, line 221, in voidresp Module ftplib, line 207, in getresp Module ftplib, line 193, in getmultiline Module ftplib, line 183, in getline EOFError Any help in catching and ignoring this error would be greatly appreciated. Regards Jon -- http://mail.python.org/mailman/listinfo/python-list
Help counting the total number of dictionaries inside a list that contain a specified key value
Hi All, I have the following list containing dictionaries and I would like to be able to count the total number of dictionaries I have that contain a certain value set for the 'level' key: [{'mod_title': u'Introduction to Human Anatomy', 'level': u'1', 'modcode': u'ANAT1003', 'deptleveltext': u'', 'deptlevelheader': u'Level 1 Courses', 'subj_code': u'AE'}, {'mod_title': u'Developmental Neurobiology', 'level': u'2', 'modcode': u'ANAT2008', 'deptleveltext': u'', 'deptlevelheader': u'Level 2 Courses', 'subj_code': u'AE'}, {'mod_title': u'Human Neuroanatomy', 'level': u'2', 'modcode': u'ANAT2010', 'deptleveltext': u'', 'deptlevelheader': u'Level 2 Courses', 'subj_code': u'AE'}, {'mod_title': u'Human Anatomy and Embryology', 'level': u'2', 'modcode': u'ANAT2050', 'deptleveltext': u'', 'deptlevelheader': u'Level 2 Courses', 'subj_code': u'AE'}, {'mod_title': u'Ethics of Fertility and Embryo Research', 'level': u'2', 'modcode': u'ANAT2099', 'deptleveltext': u'', 'deptlevelheader': u'Level 2 Courses', 'subj_code': u'AE'}, {'mod_title': u"Man's Place in Nature 1750-1900", 'level': u'23', 'modcode': u'HMED3001', 'deptleveltext': u'', 'deptlevelheader': u'Level 2/3 Courses', 'subj_code': u'AE'}, {'mod_title': u'Medicine, Disease and Society, Antiquity to Renaissance ', 'level': u'23', 'modcode': u'HMED3003', 'deptleveltext': u'', 'deptlevelheader': u'Level 2/3 Courses', 'subj_code': u'AE'}, {'mod_title': u'Madness and Society', 'level': u'23', 'modcode': u'HMED3004', 'deptleveltext': u'', 'deptlevelheader': u'Level 2/3 Courses', 'subj_code': u'AE'}] For example I'd like to kow how many dictionaries there are with a level 1, 2 , 23 & 3 etc. How would one go about achieveing this? Hope someone can help. Cheers Jon -- http://mail.python.org/mailman/listinfo/python-list
Re: Help counting the total number of dictionaries inside a list that contain a specified key value
Many thanks for all your reponses, much appreciated. I'll get back to you on which is the best for me. BTW - yes John thats exactly what I wanted. Cheers Jon Jon Bowlas wrote: > For example I'd like to kow how many dictionaries there are with a > level 1, 2 , 23 & 3 etc. How would one go about achieveing this? > > Hope someone can help. sum(u'Level 2 Courses' in dct for dct in yourlist) Christian 2008/8/12 Jon Bowlas <[EMAIL PROTECTED]>: > Hi All, > > I have the following list containing dictionaries and I would like to > be able to count the total number of dictionaries I have that contain > a certain value set for the 'level' key: > > [{'mod_title': u'Introduction to Human Anatomy', 'level': u'1', > 'modcode': u'ANAT1003', 'deptleveltext': u'', 'deptlevelheader': > u'Level 1 Courses', 'subj_code': u'AE'}, {'mod_title': u'Developmental > Neurobiology', 'level': u'2', 'modcode': u'ANAT2008', 'deptleveltext': > u'', 'deptlevelheader': u'Level 2 Courses', 'subj_code': u'AE'}, > {'mod_title': u'Human Neuroanatomy', 'level': u'2', 'modcode': > u'ANAT2010', 'deptleveltext': u'', 'deptlevelheader': u'Level 2 > Courses', 'subj_code': u'AE'}, {'mod_title': u'Human Anatomy and > Embryology', 'level': u'2', 'modcode': u'ANAT2050', 'deptleveltext': > u'', 'deptlevelheader': u'Level 2 Courses', 'subj_code': u'AE'}, > {'mod_title': u'Ethics of Fertility and Embryo Research', 'level': > u'2', 'modcode': u'ANAT2099', 'deptleveltext': u'', 'deptlevelheader': > u'Level 2 Courses', 'subj_code': u'AE'}, {'mod_title': u"Man's Place > in Nature 1750-1900", 'level': u'23', 'modcode': u'HMED3001', > 'deptleveltext': u'', 'deptlevelheader': u'Level 2/3 Courses', > 'subj_code': u'AE'}, {'mod_title': u'Medicine, Disease and Society, > Antiquity to Renaissance ', 'level': u'23', 'modcode': u'HMED3003', > 'deptleveltext': u'', 'deptlevelheader': u'Level 2/3 Courses', > 'subj_code': u'AE'}, {'mod_title': u'Madness and Society', 'level': > u'23', 'modcode': u'HMED3004', 'deptleveltext': u'', > 'deptlevelheader': u'Level 2/3 Courses', 'subj_code': u'AE'}] > > For example I'd like to kow how many dictionaries there are with a > level 1, 2 , 23 & 3 etc. How would one go about achieveing this? > > Hope someone can help. > > Cheers > > Jon > -- http://mail.python.org/mailman/listinfo/python-list
Re: Help counting the total number of dictionaries inside a list that contain a specified key value
Hrmm, any ideas why I'd be getting 'SyntaxError: invalid syntax' for both of these? > sum(u'Level 2 Courses' in dct for dct in yourlist) > q = set(['1']); print q, sum(d.get('level') in q for d in thelist) The error occurs at the 'for' I'm afraid I can't use Peters suggestion as I'm using python 2.3 and it doesn't have the collection module. Thanks anyway. Cheers Jon 2008/8/12 Jon Bowlas <[EMAIL PROTECTED]>: > Many thanks for all your reponses, much appreciated. > > I'll get back to you on which is the best for me. > > BTW - yes John thats exactly what I wanted. > > Cheers > > Jon > > Jon Bowlas wrote: >> For example I'd like to kow how many dictionaries there are with a >> level 1, 2 , 23 & 3 etc. How would one go about achieveing this? >> >> Hope someone can help. > > sum(u'Level 2 Courses' in dct for dct in yourlist) > > Christian > > 2008/8/12 Jon Bowlas <[EMAIL PROTECTED]>: >> Hi All, >> >> I have the following list containing dictionaries and I would like to >> be able to count the total number of dictionaries I have that contain >> a certain value set for the 'level' key: >> >> [{'mod_title': u'Introduction to Human Anatomy', 'level': u'1', >> 'modcode': u'ANAT1003', 'deptleveltext': u'', 'deptlevelheader': >> u'Level 1 Courses', 'subj_code': u'AE'}, {'mod_title': u'Developmental >> Neurobiology', 'level': u'2', 'modcode': u'ANAT2008', 'deptleveltext': >> u'', 'deptlevelheader': u'Level 2 Courses', 'subj_code': u'AE'}, >> {'mod_title': u'Human Neuroanatomy', 'level': u'2', 'modcode': >> u'ANAT2010', 'deptleveltext': u'', 'deptlevelheader': u'Level 2 >> Courses', 'subj_code': u'AE'}, {'mod_title': u'Human Anatomy and >> Embryology', 'level': u'2', 'modcode': u'ANAT2050', 'deptleveltext': >> u'', 'deptlevelheader': u'Level 2 Courses', 'subj_code': u'AE'}, >> {'mod_title': u'Ethics of Fertility and Embryo Research', 'level': >> u'2', 'modcode': u'ANAT2099', 'deptleveltext': u'', 'deptlevelheader': >> u'Level 2 Courses', 'subj_code': u'AE'}, {'mod_title': u"Man's Place >> in Nature 1750-1900", 'level': u'23', 'modcode': u'HMED3001', >> 'deptleveltext': u'', 'deptlevelheader': u'Level 2/3 Courses', >> 'subj_code': u'AE'}, {'mod_title': u'Medicine, Disease and Society, >> Antiquity to Renaissance ', 'level': u'23', 'modcode': u'HMED3003', >> 'deptleveltext': u'', 'deptlevelheader': u'Level 2/3 Courses', >> 'subj_code': u'AE'}, {'mod_title': u'Madness and Society', 'level': >> u'23', 'modcode': u'HMED3004', 'deptleveltext': u'', >> 'deptlevelheader': u'Level 2/3 Courses', 'subj_code': u'AE'}] >> >> For example I'd like to kow how many dictionaries there are with a >> level 1, 2 , 23 & 3 etc. How would one go about achieveing this? >> >> Hope someone can help. >> >> Cheers >> >> Jon >> > -- http://mail.python.org/mailman/listinfo/python-list