[Tutor] Adding items from a cursor to a dict?

2012-11-12 Thread Khalid Al-Ghamdi
Hi all,
How would you go about adding items from a cursor to a dictionary?

i tried this but to no avail:

>>> cur.execute('select * from schedule limit 10')

>>> for i in range(len(cur.fetchall())):
d[i]=cur.fetchall()[i]

Traceback (most recent call last):
  File "", line 2, in 
d[i]=cur.fetchall()[i]
IndexError: list index out of range

Thanks
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Adding items from a cursor to a dict?

2012-11-12 Thread Alan Gauld

On 12/11/12 08:29, Khalid Al-Ghamdi wrote:

Hi all,
How would you go about adding items from a cursor to a dictionary?

i tried this but to no avail:

 >>> cur.execute('select * from schedule limit 10')

 >>> for i in range(len(cur.fetchall())):
d[i]=cur.fetchall()[i]



The second fetchall() won't return anything because you already fetched 
all there was to fetch in the first call.


But why would you want a dictionary indexed by sequence number? You'd be 
better off with a list, which is what fetchall() gives you..


The normal pattern would be

for row in cur.fetchall():
d[ row[0] ] = row   # assuming row[0] is the desired key

or similar.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Adding items from a cursor to a dict?

2012-11-12 Thread Timo

Op 12-11-12 09:29, Khalid Al-Ghamdi schreef:

Hi all,
How would you go about adding items from a cursor to a dictionary?
There is a nice buitin way, with example here: 
http://docs.python.org/2/library/sqlite3.html#sqlite3.Row


It's not a real dictionary though, but it can act like it. Also, the 
docs say the following:

"""
If returning a tuple doesn’t suffice and you want name-based access to 
columns, you should consider setting row_factory to the highly-optimized 
sqlite3.Row type. Row provides both index-based and case-insensitive 
name-based access to columns with almost no memory overhead. It will 
probably be better than your own custom dictionary-based approach or 
even a db_row based solution.

"""

Timo



i tried this but to no avail:

>>> cur.execute('select * from schedule limit 10')

>>> for i in range(len(cur.fetchall())):
d[i]=cur.fetchall()[i]

Traceback (most recent call last):
File "", line 2, in 
d[i]=cur.fetchall()[i]
IndexError: list index out of range

Thanks


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] correctly encoding of BeautifulSoup content

2012-11-12 Thread Norman Khine
hello,

i have this piece of code (http://pastie.org/5366200) which uses
BeatifulSoup to scrape content from a site, the html for the example
can be seen here http://pastie.org/5366172

   short_description = soup.find('div', attrs={"class":
"short-description"})
   if short_description:
   short_desc = short_description.find('div',
attrs={"class": "std"})
   if short_desc:
   adm_product.append(short_desc.renderContents())

   long_description = soup.find('div', attrs={"class":
"box-collateral box-description"})
   if long_description:
   long_desc = long_description.find('div',
attrs={"class": "std"})
   if long_desc:
   adm_product.append(long_desc.renderContents())
   L = []
   for tag in long_desc.recursiveChildGenerator():
   if isinstance(tag,BeautifulSoup.Tag):
   L.append(tag.renderContents())
   desc = " ".join(v for v in L if v > 0)
   print desc
   adm_product.append(desc)
   else:
   adm_product.append('pas du description')

   # we get the country and producer
   for txt in product_shop.findAll(text=True):
   if re.search('Origine',txt,re.I):
   origin = txt.next.strip()
   try:
   country, producer = origin.split(', ')
   except Exception, e:
   pass
   else:
   adm_product.append(country)
   adm_product.append(producer)

when i print the adm_product list i get:

['002267', 'Barre chocolat au lait fourr\xc3\xa9e \xc3\xa0 la
cr\xc3\xa8me de lait25g, bio et \xc3\xa9quitableProduit
bio contr\xc3\xb4l\xc3\xa9 par Bio Inspecta', 'CHOKICHOC : la
barre de chocolat au lait, fourrée à la crème de
lait CHOKICHOC : la barre de chocolat au lait, fourrée
à la crème de lait  Exquis mélange des plus fins
cacaos et de l’aromatique sucre bio du Paraguay, CHOKICHOC est
composée exclusivement de matières premières
cultivées sans additif ni arôme artificiel. Tous les
ingrédients proviennent de cultures biologiques.
Légère, fondante, idéale pour le
goûter, un vrai délice! Légère,
fondante, idéale pour le goûter, un vrai délice!
La commercialisation des barres CHOKICHOC garantit un prix minimum
pour le producteur, des contrats d’achats à long terme
ainsi que le préfinancement partiel de la récolte.',
'0,90\xc2\xa0',
u'/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/0/0/002267_2.jpg',
u'Burkina Faso', u'Cercle des S\xe9cheurs']

my list item[1] is correctly encoded, but item[2] is not; nor are the
last 2 items

what am i missing?

thanks
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Questions about classes

2012-11-12 Thread brandon w
I have been trying to understand classes. I have been studying from a book
I picked up recently.
I have two questions about them.

1. I saw in the book an assignment written like this:

class HumanBeing:
def makeName(self, name):
  *self.name = name*
*
*
Why is it not written like this?:

class HumanBeing:
def makeName(self, name):
*  name = self.name*
*
*
2. Why use a class in the first place? What is the purpose of constructing
a class instead of just writing a program with a bunch of functions?


Thanks,

Brandon
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Questions about classes

2012-11-12 Thread Mark Lawrence

On 13/11/2012 02:49, brandon w wrote:

I have been trying to understand classes. I have been studying from a book
I picked up recently.
I have two questions about them.

1. I saw in the book an assignment written like this:

class HumanBeing:
 def makeName(self, name):
   *self.name = name*
*
*
Why is it not written like this?:

class HumanBeing:
 def makeName(self, name):
*  name = self.name*
*
*
2. Why use a class in the first place? What is the purpose of constructing
a class instead of just writing a program with a bunch of functions?


Thanks,

Brandon



This is not a Python question, so please do some research into something 
like object orientated vs functional vs procedural programming styles. 
When you've read and misunderstood, come back and ask again, and we'll 
explain The Zen of Python, specifically "practicality beats purity" :)


--
Cheers.

Mark Lawrence.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Questions about classes

2012-11-12 Thread R. Alan Monroe

> 2. Why use a class in the first place? What is the purpose of
> constructing a class instead of just writing a program with a bunch
> of functions?

Sometimes, you DO just write programs with functions.

A class can be useful if you have a bunch of a thing. Like a monster.
Each monster can know its own location, hitpoints, etc.

Alan

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] functions and iterations

2012-11-12 Thread Rufino Beniga
def IterateLogistic(x,r,n):
for i in xrange(n):
x = r*(1-x)
if i = n:
print x

I want this function to take in x and r which can be any two real numbers
and after a certain number of iterations (n), the function should print the
current state which is x. I tried this function and it doesn't do anything.
May you please tell me what i did wrong?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] functions and iterations

2012-11-12 Thread xDog Walker
On Monday 2012 November 12 19:56, Rufino Beniga wrote:
> def IterateLogistic(x,r,n):
>     for i in xrange(n):
>         x = r*(1-x)
>         if i = n:
>             print x
>
> I want this function to take in x and r which can be any two real numbers
> and after a certain number of iterations (n), the function should print the
> current state which is x. I tried this function and it doesn't do anything.
> May you please tell me what i did wrong?
Python 2.7.2 (default, Oct 10 2011, 10:47:36)
[GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def IterateLogistic(x,r,n):
... for i in xrange(n):
... x = r*(1-x)
... if i = n:
  File "", line 4
if i = n:
 ^
SyntaxError: invalid syntax
>>> print x  
-- 
Yonder nor sorghum stenches shut ladle gulls stopper torque wet 
strainers.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] functions and iterations

2012-11-12 Thread xDog Walker
On Monday 2012 November 12 21:07, you wrote:
> I tried it with i == n as well and it still doesnt work :/

Check the documentation on range and xrange and you will find out why i never 
equals n.

>>> n = 5
>>> range(n)
[0, 1, 2, 3, 4]
>>> for i in xrange(n): print i
...
0
1
2
3
4
>>>
-- 
Yonder nor sorghum stenches shut ladle gulls stopper torque wet 
strainers.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] writing files using modules and functions

2012-11-12 Thread Rufino Beniga
def MatInv(arr,file):
f = open('file.txt','w')
f.write(arr)
f.close()

So I'm trying to write a module that will take a matrix (arr) and write it
to a text file.
The above module is called MatrixIO.py

#first I import it

import MatrixIO

#Then i call the function MatInv with matrix(a) and file name (doc) as the
arguments
MatInv(a,doc)

It creates a file called txt and it shows only boxes. What am I doing wrong?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor