python 给定0 <X <10 ** 26范围内的整数返回给定数字的字符串表示。 <br/>赞:25161045656 =>'二十五bil

给定0 <X <10 ** 26范围内的整数返回给定数字的字符串表示。 <br/>赞:25161045656 =>'二十五亿一百六十一百万四十五数千六百五十六'

int_to_english.rb
$numbers = {0 => "", 1 => "one", 2 => "two", 3 => "three",
                        4 => "four", 5 => "five", 6 => "six", 7 => "seven",
                        8 =>  "eight", 9 => "nine", 10 => "ten",
                        11 => "eleven", 12 => "twelve", 13 => "thirteen",
                        14 => "fourteen", 15 => "fifteen", 16 => "sixteen",
                        17 => "seventeen", 18 => "eighteen", 19 => "nineteen",
                        20 => "twenty", 30 => "thirty", 40 => "forty",
                        50 => "fifty", 60 => "sixty",
                        70 => "seventy", 80 => "eighty",
                        90 => "ninety", 10**2 => "hundred"}

$large_numbers = {1 => "", 10**3 => "thousand", 10**6 => "million",
                   10**9 => "billion", 10**12 => "trillion",
                   10**15 => "quadrillion", 10**18 => "quintillion",
                   10**21 => "sextillion", 10**24 => "septillion"}


def small_number_to_word(number)
  english = ""

  if number.abs.to_s.length > 2
    english << $numbers[(number % 1000 - number % 100) / 100] + " " + $numbers[100] + " "
  end

  if $numbers.keys.include?(number % 100) and number != 100
    english << $numbers[number % 100]
    return english.strip
  end

  english += $numbers[number % 100 - number % 10] + " " + $numbers[number % 10] + " "

  return english.strip
end

def int_to_english(number)
  english = ""
  large_num = 1
  temp_list = []

  while number != 0
    temp_list << $large_numbers[large_num] + " "
    temp_list << small_number_to_word(number % 1000) + " "

    number = number / 1000
    large_num = large_num * 1000
  end

  temp_list.reverse!
  temp_list.each do |string|
    english << string
  end

  return english.strip
end
int_to_english.py
numStrList = {0: "", 1: "one", 2: "two", 3: "three",
                        4: "four", 5: "five", 6: "six", 7: "seven",
                        8:  "eight", 9: "nine", 10: "ten",
                        11: "eleven", 12: "twelve", 13: "thirteen",
                        14: "fourteen", 15: "fifteen", 16: "sixteen",
                        17: "seventeen", 18: "eighteen", 19: "nineteen",
                        20: "twenty", 30: "thirty", 40: "forty",
                        50: "fifty", 60: "sixty",
                        70: "seventy", 80: "eighty",
                        90: "ninety", 10**2: "hundred"}

largeNumStrList = {1: "", 10**3: "thousand", 10**6: "million",
                   10**9: "billion", 10**12: "trillion",
                   10**15: "quadrillion", 10**18: "quintillion",
                   10**21: "hexillion", 10**24: "heptillion"}


def smallNumberToWord(number):
    """Returns the string representation of a given integer
    input: 0 < X < 1000"""

    numWord = ""

    if len(str(abs(number))) > 2:
        numWord += numStrList[(number % 1000 - number % 100) / 100] + " " + \
            numStrList[100] + " "

    if number % 100 in numStrList.keys() and number != 100:
        numWord += numStrList[number % 100]
        return numWord.strip()

    numWord += numStrList[number % 100 - number % 10] + " " + \
        numStrList[number % 10] + " "

    return numWord.strip()


def numberToWord(number):
    """
    Returns the string representation of a given integer
    input: int 0 < X < 10**24
    """
    numWord = ""
    largeNum = 1
    tempList = []

    while number != 0:
        tempList.append(largeNumStrList[largeNum] + " ")
        tempList.append(smallNumberToWord(number % 1000) + " ")

        number /= 1000
        largeNum *= 1000

    tempList.reverse()
    for string in tempList:
        numWord += string

    return numWord.strip()

# MAIN function
if __name__ == '__main__':
    print numberToWord(25161045656)

python 读取csv文件并将其序列化为字典列表的脚本{column:value}然后可以将dicts用于计数或cr

读取csv文件并将其序列化为字典列表的脚本{column:value}然后可以使用dicts进行计数或创建其他统计信息。

inspectCSV.py
#!/usr/bin/env python
# encoding: utf-8
"""
csvreader.py

2013-08-27

Script that reads a csv file and serializes it into a list of dictionaries {column: value}
The dicts can then be used for counting or to create other stats. 

Note: spaces in file path should be represented simply as spaces (no escapes)

How: substitute the path of **filename** and run the script.
 
"""



import csv

filename = "test.csv"

f = open(filename, 'rU') # rU: http://www.gossamer-threads.com/lists/python/dev/723649

bag = []

try:
    reader = csv.DictReader(f)
    for row in reader:
        bag.append(row)
finally:
    f.close()
  
	
print "There are %d statements" % len(bag)

keys = bag[0].keys()

print "There are %d keys: %s" % (len(keys), ", ".join(["|"+x+"|" for x in keys]))


def getTotUniqueEl(bag, key):
	exit = []
	for x in bag:
		if x[key] not in exit:
			exit += [x[key]]
	return sorted(exit)


for x in keys:
	els = getTotUniqueEl(bag, x)
	print "*" * 10
	print "The key |%s| has %d unique elements" % (x, len(els))
	print els
	
	

python 登录V2EX领取每日奖励

登录V2EX领取每日奖励

v2ex_auto_login.py
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import requests

username = '' ###账号###
password = '' ###密码###
login_url = 'http://v2ex.com/signin' ###如V2EX设置了使用 SSL,必须改 https###
index_url = 'http://v2ex.com' ###同上###
mission_url = 'http://www.v2ex.com/mission/daily' ###同上###
UA = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) \
Chrome/27.0.1453.116 Safari/537.36"
headers = {
		"User-Agent": "UA",
		"Host": "v2ex.com",
		"Origin": "http://v2ex.com",
		"Referer": "http://www.v2ex.com/signin"
	}
v2ex_session = requests.Session()

def make_soup(url, tag, name):
	page = get_page(url)
	soup = BeautifulSoup(page)
	what_we_got = soup.find(attrs={tag:name})
	return what_we_got

def get_page(url):
	page = v2ex_session.get(url, headers=headers, verify=False).text
	return page

def mix_post_info(url):
	once_value = make_soup(url, 'name', 'once')['value'].encode('ascii')
	post_info = {
			"next": "/",
			"u": username,
			"p": password,
			"once": once_value,
			"next": "/"
		}
	return post_info

def try_login(url):
	post_info = mix_post_info(url)
	resp = v2ex_session.post(url, data=post_info, headers=headers, verify=False)
	if check_balance(index_url):
		return True
	else:
		return False

def money_link(url):
	short_url = make_soup(url, 'class', 'super normal button')['onclick']
	first_quote = short_url.find("'")
	last_quote = short_url.find("'", first_quote+1)
	short_url = short_url[first_quote+1:last_quote]
	return index_url + short_url

def check_balance(url):
	money_tag = make_soup(url, 'class', 'balance_area')
	if money_tag:
		money = money_tag.contents[0].strip() + money_tag.contents[2].strip()
		return money
	else:
		return None

def check_and_do():
	if try_login(login_url):
		print 'login successfully...'
		print 'current balance: ' + check_balance(index_url)
		mission = make_soup(index_url, 'class', 'icon-gift')
		if mission:
			print 'now take todays money...'
			get_money = money_link(mission_url)
			print 'update balance: ' + check_balance(get_money)
		else:
			print 'already take todays money...'
	else:
		print 'login fail...'

check_and_do()

python 用pc扬声器通过python唱一首歌

用pc扬声器通过python唱一首歌

pysong.py
#!/usr/bin/env python
#coding=utf-8

from ctypes import *
beep = windll.kernel32.Beep

class pySong(object):
    __pitchhz = {}
    __pianohz = {}
    __keys_s = ('a', 'a#', 'b', 'c', 'c#', 'd', 'd#', 'e', 'f', 'f#', 'g', 'g#')
    __keys_f = ('a', 'bb', 'b', 'c', 'db', 'd', 'eb', 'e', 'f', 'gb', 'g', 'ab')
    __simple_equal = {1:0, "1#":1, 2:2, "2#":2, 3:4, 4:5, "4#":6, 5:7, "5#":8, 6:9, "6#":10, 7:11}
    
    _bpm = 120
    
    def __init__(self, bpm=120):
        self._bpm = bpm
        # build pitch hz map
        for k in range(88):
            freq = 27.5 * 2.0 **(k/12.0)
            oct = (k+9) // 12
            noteS = '%s%u' % (self.__keys_s[k%12], oct)
            self.__pitchhz[noteS] = freq
            noteF = '%s%u' % (self.__keys_f[k%12], oct)
            self.__pitchhz[noteF] = freq
            self.__pianohz[k] = freq
        
    def playSimple(self, simpleScore, octane=5):
        '''
        notes range from 1-7. H stands for higher otance, L stands for lower
        octane, S for half beat, Q for quarter beat, D for double beats
        '''
        hzmsList = self.parseSimpleScore(simpleScore, octane)
        self.playHzMsList(hzmsList)
        
    def playSPN(self, spnTupleList):
        beatTime = 60000 // self._bpm        
        for spnTuple in spnTupleList:
            key = spnTuple[0]
            freq = 0
            if key <> 'r':
                freq = self.__pitchhz[key]
            time = beatTime // spnTuple[1]
            beep(int(freq), time)                

    def playHzMsList(self, hzmsList):
        for hzms in hzmsList:
            beep(int(hzms[0]), hzms[1])
    
    def parseSimpleScore(self, score, octane):
        if not score:
            raise Error("null input")
        scoreArr = []
        l = len(score)
        index = 0
        beatTime = 60000 // self._bpm
        while(index < l):
            actualOctane = octane
            actualBeatTime = beatTime
            note = int(score[index])
            while(index + 1 < l and not score[index+1].isdigit()):
                index = index + 1
                decorator = score[index].upper()
                if decorator == "H":
                    actualOctane = actualOctane + 1
                elif decorator == "L":
                    actualOctane = actualOctane - 1
                elif decorator == "S":
                    actualBeatTime = actualBeatTime // 2
                elif decorator == "Q":
                    actualBeatTime = actualBeatTime // 4
                elif decorator == "D":
                    actualBeatTime = actualBeatTime * 2
                elif decorator == "W":
                    actualBeatTime = actualBeatTime * 4
                elif decorator == "#":
                    note = str(note) + "#"
                else:
                    raise Error("simple note syntax error")
            scoreArr.append((self.__convertSimpleNoteToFeq(note, actualOctane), actualBeatTime))
            index = index + 1
        return scoreArr
    
    def __convertSimpleNoteToFeq(self, simpleNote, octane):
        if (str(simpleNote).isdigit()) and ( simpleNote < 1 or simpleNote > 7):
            return 0
        base = 12 * octane - 8
        piano = base + self.__simple_equal[simpleNote]
        return self.__pianohz[piano]
        
if __name__ == '__main__':
#    mysong = pySong("ok")
#    mysong.play()
    mysong = pySong()
#    a = mysong.parseSimpleScore('76543217L6L5L4L3L2L1L', 5)
#    mysong.playHzMsList(a)
    mysong._bpm = 120
    #mysong.playSimple("12345671H2H3H4H5H6H7H")
    mysong.playSimple("3Q2#Q3Q2#Q3Q7LQ2Q1Q6LW1L3LQ6LQ7L03L5#LQ7LQ103LQ3Q2#Q3Q2#Q3Q7LQ2Q1Q6LW1L3LQ6LQ7L03L1Q7LQ6L0", octane = 6)
    #mysong.playSimple("51HQ6Q553q5q6q1hq5565q3q22")
    #mysong.playSimple("12311231345034505Q6Q5Q4Q315Q6Q5Q4Q3125L1025L1", octane = 6)
    #mysong.playSimple("5330S4220S123455505330S4220S13553022222340S333334505330S4220S13551D")
    song1 = (
  ('bb4', 8),
  ('g5', 2), ('f5', 8), ('g5', 8), ('f5', 8/3), ('eb5', 4), ('bb4', 8),
  ('g5', 4), ('c5', 8), ('c6', 4), ('g5', 8), ('bb5', 8/3), ('ab5', 4), ('g5', 8),
  ('f5', 8/3), ('g5', 4), ('d5', 8), ('eb5', 8/3), ('c5', 8/3),
  ('bb4', 8), ('d6', 8), ('c6', 8), ('bb5', 16), ('ab5', 16), ('g5', 16), ('ab5', 16), ('c5', 16), ('d5', 16), ('eb5', 8/3),
)

    #mysong.playSPN(song1)
    
            

python django存储库模式

django存储库模式

repositories.py
from django.contrib.sites.models import Site


class Object(object):
    def __init__(self, model, key):
        self.model = model
        self.key = key

    def __call__(self, *args, **kwargs):
        params = {}
        params[self.key] = args[0]
        return self.model.objects.get(**params)

class Repository(object):
    def __init__(self, model):
        self.model = model

    def get_by_param(self, key):
        return Object(self.model, key)

    def __getattr__(self, key):
        _key = key.replace('get_by_', '')
        return self.get_by_param(_key)


SiteRepository = Repository(Site)

print SiteRepository.get_by_id(1)

python oauth_google.py

oauth_google.py
#coding: utf-8

import requests
from urllib import urlencode
import json
from subprocess import Popen
from flask import Flask,redirect,request

client_id = "your client id"
client_secret = "your client secret"
redirect_uri = "http://your_url/authorized"
base_url = r"https://accounts.google.com/o/oauth2/"
authorization_code = ""
access_token = ""

app = Flask(__name__)
"""
Retrieving authorization_code from authorization API.
"""
@app.route("/login")
def login():
  authorization_code_req = {
    "response_type": "code",
    "client_id": client_id,
    "redirect_uri": redirect_uri,
    "scope": (r"https://www.googleapis.com/auth/userinfo.profile" +
              r" https://www.googleapis.com/auth/userinfo.email" +
              r" https://www.googleapis.com/auth/calendar")
    }

  r = requests.get(base_url + "auth?%s" % urlencode(authorization_code_req),
                   allow_redirects=False)
  url = r.headers.get('location')
  print url
  return redirect(url)


def retrieve_tokens(authorization_code):
  access_token_req = {
    "code" : authorization_code,
    "client_id" : client_id,
    "client_secret" : client_secret,
    "redirect_uri" : redirect_uri,
    "grant_type": "authorization_code",
    }
  content_length=len(urlencode(access_token_req))
  access_token_req['content-length'] = str(content_length)

  r = requests.post(base_url + "token", data=access_token_req)
  data = json.loads(r.text)
  return data











@app.route("/authorized")
def authorized():
    code =  request.args["code"]
    data = retrieve_tokens(code)
    access_token = data["access_token"]
    print access_token
    print "end"

    authorization_header = {"Authorization": "OAuth %s" % access_token}
    r = requests.get("https://www.googleapis.com/oauth2/v2/userinfo", 
      headers=authorization_header)
    return r.text



if __name__ == '__main__':
     app.run(debug=True,port=8000)

python 在pygame中绘制TMX图块并将其保存为图像

在pygame中绘制TMX图块并将其保存为图像

render_tmx.py
import pygame, pytmx, argparse

def draw_tmx(tmx, window):
  # For each layer
    for l in xrange(0, len(tmx.tilelayers)):
        # For each y tile coordinate
        for y in xrange(0, tmx.height):
            # For each x tile coordinate
            for x in xrange(0, tmx.width):
                # try not strictly necessary, but a hangover from some old bad code
                try:
                    tile = tmx.getTileImage(x, y, l)
                except Exception, e:
                    print e
                    continue
                # If there is no tile to draw, tile will be 0
                if tile:
                    x_pos = x * tmx.tilewidth
                    # pygame renders tiles from top left and Tiled renders them
                    # from bottom left. This means that if the tile image is
                    # taller than the tile height, pygame will draw it downwards
                    # instead.
                    y_pos = (y * tmx.tileheight) - tile.get_height() + tmx.tileheight
                    window.blit(tile, (x_pos, y_pos))

if __name__ == "__main__":
    p = argparse.ArgumentParser()
    p.add_argument("tmx_file")
    p.add_argument("output_file")
    args = p.parse_args()

    pygame.init()
    # We can't load_pygame yet because we haven't set our display up and we
    # can't do that until we've figured out what size it needs to be..
    tmx = pytmx.tmxloader.load_tmx(args.tmx_file)
    window = pygame.display.set_mode((
      tmx.width * tmx.tilewidth, tmx.height * tmx.tileheight))
    tmx = pytmx.tmxloader.load_pygame(args.tmx_file, pixelalpha=True)
    draw_tmx(tmx, window)
    pygame.display.flip()
    pygame.image.save(window, args.output_file)

python HTML正则表达式标记匹配器

RegExp将匹配同一元素中的开始和结束标记。用于替换HTML元素字符串中的标记。对于sublime find和replace这样的东西很有用。

elementMatcher

# 'elem' Should Be Replaced With the name of the tag to matched.

/<\/?elem>/

python reddit_comments.py

wil_alert.py
import time
import re
from optparse import OptionParser
from reddit_comments import CommentFetcher, comment_link

alert_re = re.compile("wil wheaton wil wheaton wil wheaton", re.I)

def alert(comment):
    print "================== WIL WHEATON ALERT =================="
    print "FROM: " + comment["author"]
    print
    print "BODY:"
    print comment["body"]
    print
    print "URL: " + comment_link(comment)
    print "======================================================="

def run(verbose=False):
    def log(text):
        if verbose:
            print text

    cf = CommentFetcher()
    while True:
        log("Fetching new comments...")
        comments = cf.fetch()
        for comment in comments:
            log("Got comment {0}".format(comment["id"]))
            if alert_re.search(comment["body"]):
                alert(comment)
            
        time.sleep(35)
        
def main():
    parser = OptionParser()
    parser.add_option("-v", "--verbose",
                      action="store_true", dest="verbose", default=False,
                      help="enable verbose status messages")
 
    (options, args) = parser.parse_args()
    run(options.verbose)
    
if __name__=="__main__":    
    main()
reddit_comments.py
import time
from urllib2 import urlopen, quote
import json

def fetch_comments(after=None):
    url = "http://reddit.com/comments.json"
    if after:
        url += "?after={0}".format(quote(after))
        
    #print "... Fetching {0} ...".format(url)
    data = json.load(urlopen(url))["data"]
    comments = [w["data"] for w in data["children"]]
    
    return comments, data["after"]

def comment_link(comment):
    return "http://reddit.com/comments/{0}/comment/{1}".format(comment["link_id"], comment["parent_id"])

class CommentFetcher(object):
    def __init__(self, last=None):
        self.last = last

    def fetch(self):
        if self.last is None:
            comments, after = fetch_comments()
        else:
            comments = []
            after = None
            done = False
            while not done:
                cs, after = fetch_comments(after)
                for comment in cs:
                    if comment["id"] == self.last:
                        done = True
                        break
                    else:
                        comments.append(comment)
                    
                time.sleep(2)

        if comments:
            self.last = comments[0]["id"]
        return comments

python Python - 时间戳

Python - 时间戳

timestamp.py
import datetime

# 2012-12-15 10:14:51.898000
print datetime.datetime.utcnow()

# The now differs from utcnow as expected
# otherwise they work the same way:
# 2012-12-15 11:15:09.205000
print datetime.datetime.now()

# You can render the timestamp to the ISO format string explicitly:
# '2012-12-15 11:15:24.984000'
str(datetime.datetime.now())

# Or you can be even more explicit to format the
# timestamp the way you like:

# 'Saturday, 15. December 2012 11:19AM'
datetime.datetime.now().strftime("%A, %d. %B %Y %I:%M%p")
# '2012-12-15'
datetime.datetime.now().strftime("%Y-%m-%d")