Python 在Delicious中快速轻松地删除质量标签

import delicious
fb = delicious.connect('<username>', '<password>')
tags = fb.tags()
for tag in tags:
  if tag['count'] == 1:
    fb.rename_tag(tag['name'], tag['deleteme'])
  if not tag['name'] == tag['name'].lower():
    login.rename_tag(tag['name'], tag['name'].lower())

#Now login to Delicious and delete the 'deleteme' tag.

Python 基本的python单元测试


import random
import unittest

class TestSequenceFunctions(unittest.TestCase):

    def setUp(self):
        self.seq = range(10)

    def testshuffle(self):
        # make sure the shuffled sequence does not lose any elements
        random.shuffle(self.seq)
        self.seq.sort()
        self.assertEqual(self.seq, range(10))

    def testchoice(self):
        element = random.choice(self.seq)
        self.assert_(element in self.seq)

    def testsample(self):
        self.assertRaises(ValueError, random.sample, self.seq, 20)
        for element in random.sample(self.seq, 5):
            self.assert_(element in self.seq)

if __name__ == '__main__':
    unittest.main()

Python 完美的Django设置文件

"""
Here's my sample Django settings for a project I recently did. Visit http://damonjablons.wordpress.com to see the explanation.
"""

import os
import socket

# Set DEBUG = True if on the production server
if socket.gethostname() == 'your.domain.com':
    DEBUG = False
else:
    DEBUG = True

TEMPLATE_DEBUG = DEBUG

ADMINS = (
    ('Damon Jablons', 'damon@fake.email.com'),
)

MANAGERS = ADMINS

# The database settings are left blank so to force the use of local_settings.py below
DATABASE_ENGINE = ''           # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = ''             # Or path to database file if using sqlite3.
DATABASE_USER = ''             # Not used with sqlite3.
DATABASE_PASSWORD = ''         # Not used with sqlite3.
DATABASE_HOST = ''             # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = ''             # Set to empty string for default. Not used with sqlite3.

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/New_York'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = False

# This dynamically discovers the path to the project
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))

# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = '/media/'

# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '%sadmin-media/' % MEDIA_URL

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'OH_NOES!'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.load_template_source',
    'django.template.loaders.app_directories.load_template_source',
#     'django.template.loaders.eggs.load_template_source',
)

# Context Processors
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.auth',
    'django.core.context_processors.media',
    'django.core.context_processors.request',
)

if DEBUG:
    TEMPLATE_CONTEXT_PROCESSORS += ('django.core.context_processors.debug',)
if USE_I18N:
    TEMPLATE_CONTEXT_PROCESSORS += ('django.core.context_processors.i18n',)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
)

if DEBUG:
    MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',)

ROOT_URLCONF = 'urls'

TEMPLATE_DIRS = ()
for root, dirs, files in os.walk(PROJECT_PATH):
    if 'templates' in dirs: TEMPLATE_DIRS += (os.path.join(root, 'templates'),)

INSTALLED_APPS = (

    # Django Applications
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.admin',
    'django.contrib.admindocs',

    # Third Party Django Applications
    'django_extensions',
    'sorl.thumbnail',
    'filebrowser',
    'chunks',
    'registration',
    
    # Project Applications
    'use',
    'wsgi',
    'and',
    'dont',
    'include',
    'the',
    'project',
    'name',
)

if DEBUG:
    INSTALLED_APPS += ('debug_toolbar',)

TEMPLATE_TAGS = (
    'sorl.thumbnail.templatetags.thumbnail',
    'scribblitt.general.templatetags.rotator_includes',
    'chunks.templatetags.chunks',
)

# SORL Settings
THUMBNAIL_EXTENSION = 'png'

# Filebrowser Settings
FILEBROWSER_URL_WWW = os.path.join(MEDIA_URL, 'uploads%s' % os.sep)
FILEBROWSER_PATH_SERVE = os.path.join(MEDIA_ROOT, 'uploads')
FILEBROWSER_URL_FILEBROWSER_MEDIA = os.path.join(MEDIA_URL, 'filebrowser%s' % os.sep)
FILEBROWSER_PATH_FILEBROWSER_MEDIA = os.path.join(MEDIA_ROOT, 'filebrowser')

# Registration App Settings
ACCOUNT_ACTIVATION_DAYS = 3
LOGIN_REDIRECT_URL = '/'

INTERNAL_IPS = (
    '127.0.0.1',
)

DEBUG_TOOLBAR_CONFIG = {
    'INTERCEPT_REDIRECTS': False,
}

try:
    from local_settings import *
except ImportError:
    pass

Python Python:使用Python AppEngine作为Twitter的代理

import os
#Python's standard Web Application Container
import wsgiref.handlers
#Template Renderder
from apptools import AppHandler
#Google's App Engine
from google.appengine.ext import webapp

import urllib2
from urllib2 import urlopen 

class RedirectHandler(webapp.RequestHandler):
  def get(self):
    data = urlopen( "http://twitter.com/statuses/user_timeline/chrisaiv.xml?count=10" ) 
    d = data.read();
    self.response.out.write( d );

def main():
  application = webapp.WSGIApplication([
	('/twitterproxy', RedirectHandler),
    debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()

Python Bresenham的线算法

def bresenham_line((x,y),(x2,y2)):
    """Brensenham line algorithm"""
    steep = 0
    coords = []
    dx = abs(x2 - x)
    if (x2 - x) > 0: sx = 1
    else: sx = -1
    dy = abs(y2 - y)
    if (y2 - y) > 0: sy = 1
    else: sy = -1
    if dy > dx:
        steep = 1
        x,y = y,x
        dx,dy = dy,dx
        sx,sy = sy,sx
    d = (2 * dy) - dx
    for i in range(0,dx):
        if steep: coords.append((y,x))
        else: coords.append((x,y))
        while d >= 0:
            y = y + sy
            d = d - (2 * dx)
        x = x + sx
        d = d + (2 * dy)
    coords.append((x2,y2))
    return coords

Python python web与瓶

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import bottle as web # http://bottle.paws.de/page/docs
DEV=True
web.debug(DEV)


@web.route("/static/:path")
def static(path):
    web.send_file(path,root="static")

@web.route('/:name#.*#')
def index(name):
    name = name or "unknown"
    web.response.content_type = 'text/html; charset=utf-8'
    web.response.COOKIES['kiki'] = name
    return """hello %(name)s
            <a href='/do/show?a=1&a=2'>show</a>""" % locals()

@web.route('/do/:cmd?')
def cmd(cmd):
    if cmd=="show":
        yield "<li>cookies : %s</li>"% str(web.request.COOKIES)
        yield "<li>get : %s</li>"%     str(web.request.GET)
        yield "<li>post : %s</li>"%    str(web.request.POST)
    else:
        web.redirect("/") #don't work with yield now ;-(

@web.route('/.*')
def fallback():
    yield "my 404"
    #~ web.abort(404, "Not Found")

@web.error(500)             # don't work for me ?!?
def fallback500(err):
    return "my error:"+str(err)

def main(useGae=False):
    if useGae:
        from google.appengine.ext.webapp import util
        util.run_wsgi_app(web.default_app())
    else:
        web.run(reloader=DEV)

if __name__=="__main__":
    main()

Python python脚本从批量文本中提取所有电子邮件地址

# this script will open a file with email addresses in it, then extract 
# those address and write them to a new file

import os
import re

# vars for filenames
filename = 'emaillist.txt'
newfilename = 'emaillist-rev.txt'

# read file
if os.path.exists(filename):
	data = open(filename,'r')
	bulkemails = data.read()
else:
	print "File not found."
	raise SystemExit

# regex = whoEver@wHerever.xxx
r = re.compile(r'(\b[\w.]+@+[\w.]+.+[\w.]\b)')
results = r.findall(bulkemails)    

emails = ""   
for x in results:
	emails += str(x)+"\n"	

# function to write file
def writefile():
	f = open(newfilename, 'w')
	f.write(emails)
	f.close()
	print "File written."

# function to handle overwrite question
def overwrite_ok():
	response = raw_input("Are you sure you want to overwrite "+str(newfilename)+"? Yes or No\n")
	if response == "Yes":
		writefile()
	elif response == "No":
		print "Aborted."
	else:
		print "Please enter Yes or No."
		overwrite_ok()

# write/overwrite
if os.path.exists(newfilename):
	overwrite_ok()		
else: 
	writefile()

Python 计算两点之间的度数(向量)

import math
radians = math.atan2(y2 - y1, x2 - x1)
degrees = math.degrees(radians)

Python Python:使用Map

# build a dictionary that maps the ordinals from 32 to 255
# to their ASCII character equivalents  eg. 33: '!'
# (note that 32 and 160 are spaces)
# Python24  by  vegaseat    10may2005
 
import operator
 
print "ASCII values of characters:"
print '-'*27  # print 27 dashes, cosmetic
 
# create an empty dictionary
charD = {}
# set keys from 32 to 255
keyList = range(32, 256)
# use map() to create the character list
# applies function chr() to every item of the list
valueList = map(chr, keyList)
# use map() to form a dictionary from the two lists
map(operator.setitem, [charD]*len(keyList), keyList, valueList)
 
print "%6s%6s%6s" % ("hex", "dec", "char")
# print the dictionary one associated pair each line
for key,value in charD.items():
    print "%6x%6d%6c" % (key, key, value)
 
print '-'*27

Python Python:TIME模块

## The time module provides a portable interface to time functions on the system on which the program is executing. The following examples illustrate some of the most common uses of the time module.

##The time.time() function returns the current system time in terms of the number of seconds since the UTC (Coordinated Universal Time). This value is typically collected at various points in the program and is used in delta operations to determine the amount of time since an event occurred.
>>>print time.time()
1155333864.11

##The time.localtime(secs) function returns the time, specified by secs since the UTC, in the form of tuple (year, month, day, hour, minute, second, day of week, day of year, daylight savings). If no time is specified, the current time is used as follows:
>>>print time.localtime()
(2006, 8, 11, 16, 4, 24, 4, 223, 1)

##The time.ctime(secs) function returns the time, specified by secs since the UTC, as a formatted, printable string. If no time is specified, then the current time is used as shown here:
>>>print time.ctime()
Fri Aug 11 16:04:24 2006

##The time.clock() function returns the current CPU time as a floating-point number that can be used for various timing functions:
>>>print time.clock()
5.02857206712e-006

##The time.sleep(sec) function forces the current process to sleep for the number of seconds specified by the floating-point number secs:
>>>time.sleep(.5)