Skip to content

Instantly share code, notes, and snippets.

import xml.etree.cElementTree as ET
# Pyhton implementation: import xml.etree.ElementTree as ET
filename = 'myfile.xml'
tag = ''
text = ''
attrs = {}
# Document Tree XML parser (load the entire document into memory)
tree = ET.parse(filemane)
@dsaiztc
dsaiztc / pymongo.py
Last active August 29, 2015 14:23
Python driver for MongoDB: PyMongo. http://api.mongodb.org/python/current/
"""
MongoDB database installed on ~/Development/MongoDB/
To run MongoDB just type:
mongod --dbpath ~/Development/MongoDB/db/
cd <mongodb installation dir>
./bin/mongod --dbpath ~/Development/MongoDB/db/
"""
from pymongo import MongoClient
import csv
filename = 'file.csv'
# Read CSV
with open(filename, 'rb') as csvfile:
csvreader = csv.reader() # Common values -> delimiter=',' quotechar='"'
for row in reader:
pass
# Count the number of lines within a file
num_lines = sum(1 for line in open('myfile.txt'))
@dsaiztc
dsaiztc / delete.sql
Last active May 19, 2016 10:04
SQL basics.
DELETE FROM table_name
WHERE some_column=some_value;
@dsaiztc
dsaiztc / functions.sql
Last active August 29, 2015 14:24
SQL functions.
# Aggregate functions
COUNT(column|*)
AVG(column)
MIN(column)
MAX(column)
SUM(column)
# Mathematical functions
ABS(number)
ROUND(number)
import json
import requests
url = 'http://...'
r = requests.get(url)
r.status_code
r.headers
r.enconding
html_s = r.text # content of the server’s response
json_data = json.loads(html_s)
@dsaiztc
dsaiztc / excel.py
Last active November 4, 2015 03:30
Excel files Python management. http://www.python-excel.org/
import xlrd
datafile = "my_file.xls"
workbook = xlrd.open_workbook(datafile)
sheet = workbook.sheet_by_index(0)
data = [[sheet.cell_value(r, col)
for col in range(sheet.ncols)]
for r in range(sheet.nrows)]
@dsaiztc
dsaiztc / beautifulsoup.py
Last active August 29, 2015 14:24
Screen Scraping with BeautifulSoup for Python. http://www.crummy.com/software/BeautifulSoup/bs4/doc/
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.prettify())
tag = soup.kind_of_tag # retrieve the element with kind_of_tag (the first occurrence I suppose)
tag.name # name of the tag
tag.string # text of the tag
tag.attrs # attributes of the tag as a dictionary
tag['attribute_name'] # access to an attribute
// cd <mongodb installation dir>
// ./bin/mongo
db // display database in use (default database: test)
show dbs // Show all databases
use <database> // select database to use
// Access a collection and use shell methods
show collections // show all collections for current database
db.<collection>.find()