python n00b tips, snippets
python
>>> import urllib2
>>> p = urllib2.urlopen("http://www.google.com")
>>> c = p.read()
>>> c
>>> dir(p)
>>> exx = p.geturl()
>>> exx
'http://www.google.com.tr/?gfe_rd=cr&ei=77OxVof4Hqyo8we8qoyADw'
>>> p.headers.items()
[('content-length', '19509'), ('x-xss-protection', '1; mode=block')]
>>> from xml.dom import minidom
>>> x = minidom.parseString("<mytag>contents<children><item>x1</item><item>x2</item></children></mytag>")
>>> x
<xml.dom.minidom.Document instance at 0x7fb8d0828200>
>>> x.childNodes[0].getElementsByTagName("children")[0].getElementsByTagName("item")[1].childNodes[0].nodeValue
u'x2'
>>> xmlNY = urllib2.urlopen("http://rss.nytimes.com/services/xml/rss/nyt/InternationalHome.xml").read()
>>> parsedFromNYXML = minidom.parseString(xmlNY)
>>> parsedFromNYXML = minidom.parseString(xmlNY)
>>> g3.getElementsByTagName("item").length
20
>>> len(g3.getElementsByTagName("item"))
20
>>> import json
>>> j= '{"xx": 12, "arr": [1,2,4.5]}'
>>> json.loads(j)
def total_ups():
sum = 0
j = json.loads(reddit_front)
x = j.get("data").get("children")
for c in x:
sum += c.get("data").get("ups")
return sum
print total_ups()
urllib2.urlopen('http://rss.nytimes.com/services/xml/rss/nyt/InternationalHome.xml')
proxy = urllib2.ProxyHandler({'http': 'user:pass@ip:port'})
# cache example
import time
# complex_computation() simulates a slow function. time.sleep(n) causes the
# program to pause for n seconds. In real life, this might be a call to a
# database, or a request to another web service.
def complex_computation(a, b):
time.sleep(.5)
return a + b
# QUIZ - Improve the cached_computation() function below so that it caches
# results after computing them for the first time so future calls are faster
cache = {}
def cached_computation(a, b):
key = (a,b)
if key in cache:
return cache[key]
else:
tmp = complex_computation(a, b)
cache[key] = tmp
return tmp
# JS arr => list, tuple | JS obj => dict, set
# list, tuples ops compared to JS
a.length len(l)
a.push(item) l.append(item)
a.pop() l.pop()
a.shift() l.pop(0)
a.unshift(item) l.insert(0, item)
a.slice(start, end) l[start:end]
a.splice(start, howMany, [...]) l[start:end] = [...]