Python Tutorial

Thursday, June 7, 2012

python sort dictionary



Using sorted we can also dictionary data.



d={}
(d['a'],d['o'],d['g'])=("alpha","omega","gamma")

print d
for k in sorted( d.keys() ): 
   print k," ",d[k]

print d



Output:
{'a': 'alpha', 'g': 'gamma', 'o': 'omega'}
a   alpha
g   gamma
o   omega
{'a': 'alpha', 'g': 'gamma', 'o': 'omega'}

python sort tuple



Some example for sort tuple are given



a=[(1,"b"),(2,"a"),(1,"e")]
print a
print sorted(a)

def myTSort(d):
    return d[0] # sort according to first value

print sorted(a,key=myTSort)
print sorted(a,key=myTSort, reverse=True)
print a



Output:
[(1, 'b'), (2, 'a'), (1, 'e')]
[(1, 'b'), (1, 'e'), (2, 'a')]
[(1, 'b'), (1, 'e'), (2, 'a')]
[(2, 'a'), (1, 'b'), (1, 'e')]
[(1, 'b'), (2, 'a'), (1, 'e')]

python string array sort: pass custom function



Sorted is very easy to use. We can use both built-in and custom function for sorting. Some example are given here. Remember it always return a new array by kipping the original array



a=["Life", "is", "very","easy", "with", "python"]

def myFunction(data):
    return data[0]

print sorted(a)
print sorted(a,key=myFunction)
print sorted(a,key=len)
print sorted(a)



Output:
['Life', 'easy', 'is', 'python', 'very', 'with']
['Life', 'easy', 'is', 'python', 'very', 'with']
['is', 'Life', 'very', 'easy', 'with', 'python']
['Life', 'easy', 'is', 'python', 'very', 'with']

python sorted: sort array

I like sorted because it is easy to use, sort multi structered data and also keep the original data which very important some times
 
a=[3,2,1,4,5]
print a
print sorted(a)
print sorted(a,reverse=True)
print a


Output:
[3, 2, 1, 4, 5]
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
[3, 2, 1, 4, 5]

Access shared resource

Sometime we need to access shared document, for example when our application write to a single file on multi-thread. In this case we need to access the through locking.

This technique is useful for web crawler.
lock=threading.Lock()
def writeToFile():
    lock.acquire()
    try:
        //write data
    finally:
        lock.release()

Python Quotes

 
Here some great python quotes. You may share yours
    Perl is worse than Python because people wanted it worse - Larry Wall, Creator of Perl Python fits your brain - Bruce Eckel, Author: Thinking in Java Python is an excellent language & makes sensible compromises. - Peter Norvig. AI Life is better without braces

Saturday, January 28, 2012

Python Beautiful Soup Url extract from web page

Python Beautiful Soup Url extract from web page


from BeautifulSoup import BeautifulSoup, SoupStrainer
import re
import urllib2

def get_url_content(site_url):
    rt=""
    try:
        request = urllib2.Request(site_url) 
        f=urllib2.urlopen(request)
        content=f.read()
        f.close()
    except urllib2.HTTPError, error:
        content=str(error.read())
    return content

response=get_url_content('http://www.sust.edu/')

for link in BeautifulSoup(response, parseOnlyThese=SoupStrainer('a')):
    if link.has_key('href'):
        print link['href']




Output:

All urls under this link