Category: Python

  • python查看已经安装的模块

    方法一:

    
    >>> help('modules')
    
    Please wait a moment while I gather a list of all available modules...
    
    ....
    
    Enter any module name to get more help.  Or, type "modules spam" to search
    
    for modules whose descriptions contain the word "spam".
    

    方法二:

    >>> import sys
    
    >>> sys.modules
    
  • ip2long与long2ip

    在php中可以知道 ip2long 函数将ip转为整型,long2ip将整型转为ip,从而方便计算。

    ip分为四段,将第一段*256^3,第二段*256^2,第三段*256^1,第四段*256^0,最后相加,这样就计算出了一个唯一的值。如果都是最大值,算出来的值是

    >>> 255*256*256*256 + 255*256*256 + 255*256 + 255
    4294967295

    我们可以发现mysql中int型的取值范围是4个字节,十进制为

    0  到  4294967295

    所以所有的ipv4地址用mysql的int恰好可以完整记录

    python中互相转换的方法如下

    import socket 
    import struct
    
    def ip2long(ipstr): 
        return struct.unpack("!I", socket.inet_aton(ipstr))[0]
    
    def long2ip(ip): 
        return socket.inet_ntoa(struct.pack("!I", ip))
    

    http://hily.me/blog/2009/03/python-ip2long-long2ip/

  • 整理python的csv.reader和csv.writer

    以下脚本是读取以空格分开的字段(weight.txt)变成以逗号分隔(weight.csv)

    #!/usr/bin/env python
    #-*- coding:utf-8 -*-
    # author jpuyy.com
    import csv
    reader = csv.reader(open('weight.txt', 'rb'), delimiter=' ', quoting=csv.QUOTE_NONE)
    writer = csv.writer(open('weight.csv', 'wb'))
        for row in reader:
        writer.writerow(row)

    解决 csv 用 excel 打开乱码问题

    import codecs
    
    file_obj = open(csv_name, "wb+")
    file_obj.write(codecs.BOM_UTF8)
    f = csv.writer(file_obj)
    
    
  • Ubuntu下安装Django

    Django为流行的python web开发框架

    安装python的包管理器,easy_install

    # apt-get install python-setuptools

    可以使用下面的命令检查是否安装成功

    # easy_install --version

    显示版本信息则安装成功

    接下来使用easy_install安装Django

    # easy_install django

    使用如下命令查看django是否安装成功

    # python
    Python 2.7.3 (default, Aug 1 2012, 05:14:39)
    [GCC 4.6.3] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import django
    >>> django.VERSION
     (1, 4, 3, 'final', 0)

    出现版本信息,则表示安装成功。

  • python的入门的几个例子(下)

    http://jpuyy.com/2012/12/python-simple-programs-a.html

    http://jpuyy.com/2013/01/python-simple-programs-b.html

    例.20 素数筛选,生成器–Prime numbers sieve w/fancy generators

    生成从2到1000以内的素数

    import itertools
    
    def iter_primes():
         # an iterator of all numbers between 2 and +infinity
         numbers = itertools.count(2)
    
         # generate primes forever
         while True:
             # get the first number from the iterator (always a prime)
             prime = numbers.next()
             yield prime
    
             # this code iteratively builds up a chain of
             # filters...slightly tricky, but ponder it a bit
             numbers = itertools.ifilter(prime.__rmod__, numbers)
    
    for p in iter_primes():
        if p > 1000:
            break
        print p

    例21.xml/html解析–XML/HTML parsing

    dinner_recipe = '''<html><body><table>
    <tr><th>amt</th><th>unit</th><th>item</th></tr>
    <tr><td>24</td><td>slices</td><td>baguette</td></tr>
    <tr><td>2+</td><td>tbsp</td><td>olive oil</td></tr>
    <tr><td>1</td><td>cup</td><td>tomatoes</td></tr>
    <tr><td>1</td><td>jar</td><td>pesto</td></tr>
    </table></body></html>'''
    
    # In Python 2.5 or from http://effbot.org/zone/element-index.htm
    import xml.etree.ElementTree as etree
    tree = etree.fromstring(dinner_recipe)
    
    # For invalid HTML use http://effbot.org/zone/element-soup.htm
    # import ElementSoup, StringIO
    # tree = ElementSoup.parse(StringIO.StringIO(dinner_recipe))
    
    pantry = set(['olive oil', 'pesto'])
    for ingredient in tree.getiterator('tr'):
        amt, unit, item = ingredient
        if item.tag == "td" and item.text not in pantry:
            print "%s: %s %s" % (item.text, amt.text, unit.text)

    例28. 8皇后问题(自定义例外)8-Queens Problem (define your own exceptions)

    BOARD_SIZE = 8
    
    class BailOut(Exception):
        pass
    
    def validate(queens):
        left = right = col = queens[-1]
        for r in reversed(queens[:-1]):
            left, right = left-1, right+1
            if r in (left, col, right):
                raise BailOut
    
    def add_queen(queens):
        for i in range(BOARD_SIZE):
            test_queens = queens + [i]
            try:
                validate(test_queens)
                if len(test_queens) == BOARD_SIZE:
                    return test_queens
                else:
                    return add_queen(test_queens)
            except BailOut:
                pass
        raise BailOut
    
    queens = add_queen([])
    print queens
    print "\n".join(". "*q + "Q " + ". "*(BOARD_SIZE-q-1) for q in queens)
     例33,猜数字游戏
    import random
    
    guesses_made = 0
    
    name = raw_input('Hello! What is your name?\n')
    
    number = random.randint(1, 20)
    print 'Well, {0}, I am thinking of a number between 1 and 20.'.format(name)
    
    while guesses_made < 6:
    
        guess = int(raw_input('Take a guess: '))
    
        guesses_made += 1
    
        if guess < number:
            print 'Your guess is too low.'
    
        if guess > number:
            print 'Your guess is too high.'
    
        if guess == number:
            break
    
    if guess == number:
        print 'Good job, {0}! You guessed my number in {1} guesses!'.format(name, guesses_made)
    else:
        print 'Nope. The number I was thinking of was {0}'.format(number)
     把代码打了一遍,还得仔细再练几遍。
  • python的入门的几个例子(中)

    接着上一个http://jpuyy.com/2012/12/python-simple-programs-a.html

    例11.三引号,while循环–Triple-quoted strings, while loop

    REFRAIN = '''
    %d bottles of beer on the wall,
    %d bottles of beer,
    take one down, pass it around,
    %d bottles of beer on the wall!
    '''
    bottles_of_beer = 99
    while bottles_of_beer > 1:
        print REFRAIN % (bottles_of_beer, bottles_of_beer,
            bottles_of_beer - 1)
        bottles_of_beer -= 1

    例12.python中的类–Classes

    class BankAccount(object):
        def __init__(self, initial_balance=0):
            self.balance = initial_balance
        def deposit(self, amount):
            self.balance += amount
        def withdraw(self, amount):
            self.balance -= amount
        def overdrawn(self):
            return self.balance < 0
    my_account = BankAccount(15)
    my_account.withdraw(5)
    print my_account.balance

    执行结果是10

    例13.使用unittest模块进行单元测试–Unit test with unittest

    import unittest
    def median(pool):
        copy = sorted(pool)
        size = len(copy)
        if size % 2 == 1:
            return copy[(size - 1) / 2]
        else:
            return (copy[size/2 - 1] + copy[size/2]) / 2
    class TestMedian(unittest.TestCase):
        def testMedian(self):
            self.failUnlessEqual(median([2, 9, 9, 7, 9, 2, 4, 5, 8]), 7)
    if __name__ == '__main__':
        unittest.main()

    执行过程:将中间值计算出来与7比较,如果相等,则通过测试。

    例14.基于Doctest的测试–Doctest-based testing

    def median(pool):
        '''Statistical median to demonstrate doctest.
        >>> median([2, 9, 9, 7, 9, 2, 4, 5, 8])
        7
        '''
        copy = sorted(pool)
        size = len(copy)
        if size % 2 == 1:
            return copy[(size - 1) / 2]
        else:
            return (copy[size/2 - 1] + copy[size/2]) / 2
    if __name__ == '__main__':
        import doctest
        doctest.testmod()

    执行结果:没有输出任何东西,说明中间值是7

    例15.使用itertools模块

    from itertools import groupby
    lines = '''
    This is the
    first paragraph.
    
    This is the second.
    '''.splitlines()
    # Use itertools.groupby and bool to return groups of
    # consecutive lines that either have content or don't.
    for has_chars, frags in groupby(lines, bool):
        if has_chars:
            print ' '.join(frags)
    # PRINTS:
    # This is the first paragraph.
    # This is the second.

    例16.csv模块,元组拆分,内置函数cmp() — csv module, tuple unpacking, cmp() built-in

    import csv
    
    # write stocks data as comma-separated values
    writer = csv.writer(open('stocks.csv', 'wb', buffering=0))
    writer.writerows([
        ('GOOG', 'Google, Inc.', 505.24, 0.47, 0.09),
        ('YHOO', 'Yahoo! Inc.', 27.38, 0.33, 1.22),
        ('CNET', 'CNET Networks, Inc.', 8.62, -0.13, -1.49)
    ])
    
    # read stocks data, print status messages
    stocks = csv.reader(open('stocks.csv', 'rb'))
    status_labels = {-1: 'down', 0: 'unchanged', 1: 'up'}
    for ticker, name, price, change, pct in stocks:
        status = status_labels[cmp(float(change), 0.0)]
        print '%s is %s (%s%%)' % (name, status, pct)

    例18. 八皇后问题,递归–8-Queens Problem (recursion)

    BOARD_SIZE = 8
    
    def under_attack(col, queens):
        left = right = col
    
        for r, c in reversed(queens):
            left, right = left - 1, right + 1
    
            if c in (left, col, right):
                return True
        return False
    
    def solve(n):
        if n == 0:
            return [[]]
    
        smaller_solutions = solve(n - 1)
    
        return [solution+[(n,i+1)]
            for i in xrange(BOARD_SIZE)
                for solution in smaller_solutions
                    if not under_attack(i+1, solution)]
    for answer in solve(BOARD_SIZE):
        print answer