Python 善用Google?®æ¤œç'¢Cμ?果数ã,'å?? - å¾-

#googleの検索結果数を見る
def countWord(word):
    q = {#'q':'\"'+question+'\"',
        'q':word.encode('utf-8'),
        'v' : 1.0,
        'hl' : 'ja',
        'rsz': 'small'
    }
    url=u'http://ajax.googleapis.com/ajax/services/search/web?'+ urllib.urlencode(q)
    json_result=urlfetch.fetch(url).content
    json_result = string.replace(json_result, 'null', '"null"')
    try:
        dict_result=eval('dict('+json_result+')')        
        return dict_result['responseData']['cursor']['estimatedResultCount']
    except:
        return 0

Python 唯一ID序列类

class UniqueIdGenerator(object):
    """A dictionary-like class that can be used to assign unique integer IDs to
    names.

    Usage:
    
    >>> gen = UniqueIdGenerator()
    >>> gen["A"]
    0
    >>> gen["B"]
    1
    >>> gen["C"]
    2
    >>> gen["A"]      # Retrieving already existing ID
    0
    >>> len(gen)      # Number of already used IDs
    3
    """

    def __init__(self, id_generator=None):
        """Creates a new unique ID generator. `id_generator` specifies how do we
        assign new IDs to elements that do not have an ID yet. If it is `None`,
        elements will be assigned integer identifiers starting from 0. If it is
        an integer, elements will be assigned identifiers starting from the given
        integer. If it is an iterator or generator, its `next` method will be
        called every time a new ID is needed."""
        if id_generator is None: id_generator = 0
        if isinstance(id_generator, int):
            import itertools
            self._generator = itertools.count(id_generator)
        else:
            self._generator = id_generator
        self._ids = {}

    def __getitem__(self, item):
        """Retrieves the ID corresponding to `item`. Generates a new ID for `item`
        if it is the first time we request an ID for it."""
        try:
            return self._ids[item]
        except KeyError:
            self._ids[item] = self._generator.next()
            return self._ids[item]

    def __len__(self):
        """Retrieves the number of added elements in this UniqueIDGenerator"""
        return len(self._ids)

    def reverse_dict(self):
        """Returns the reversed mapping, i.e., the one that maps generated IDs to their
        corresponding items"""
        return dict((v, k) for k, v in self._ids.iteritems())

    def values(self):
        """Returns the list of items added so far. Items are ordered according to
        the standard sorting order of their keys, so the values will be exactly
        in the same order they were added if the ID generator generates IDs in
        ascending order. This hold, for instance, to numeric ID generators that
        assign integers starting from a given number."""
        return sorted(self._ids.keys(), key = self._ids.__getitem__)

Python Python MySQLdb Insert Id

cursor.lastrowid

Python 创建编写文件所需的目录

def ensure_dir(f):
    d = os.path.dirname(f)
    if not os.path.exists(d):
        os.makedirs(d)

Python 检查文件是否存在

try:
    file = open("testfile", 'r')
    print "File exists."
    file.close()
except IOError:
    print "File does not exist."

Python 从filepath获取文件名

srcFilename = os.path.split(srcfilepath)[1]

Python 从命令行通过dbus获取exaile的当前歌曲

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Simple script to get the current song being played by
# exaile. 
# Author: Santiago Zarate <santiago [at] zarate [dot] net [dot] ve>
# Blog: http://blog.santiago.zarate.net.ve
# 

import sys, dbus

bus = dbus.SessionBus()

try:
    remote_object = bus.get_object("org.exaile.DBusInterface","/DBusInterfaceObject")
    iface = dbus.Interface(remote_object, "org.exaile.DBusInterface")
    if(iface.status() == 'playing'):
        message = '%s - %s - %s ' % (iface.get_title(), iface.get_album(), iface.get_artist())
    else:
        message = 'Exaile is not playing'

except dbus.exceptions.DBusException, e:
    message = 'Exaile is not running: %s' % e

print message

Python 从Python中获取os命令的输出

from subprocess import Popen
from subprocess import PIPE

bla = Popen(["ls", "-l"], stdout=PIPE).communicate()[0]

Python 在python中展平[[1,),(2,),(3,)]类的列表

import operator
map(operator.itemgetter(0), [(1,),(2,)])

Python 将IP转换为Int,将Int转换为IP

def IntToDottedIP( intip ):
        octet = ''
        for exp in [3,2,1,0]:
                octet = octet + str(intip / ( 256 ** exp )) + "."
                intip = intip % ( 256 ** exp )
        return(octet.rstrip('.'))

def DottedIPToInt( dotted_ip ):
        exp = 3
        intip = 0
        for quad in dotted_ip.split('.'):
                intip = intip + (int(quad) * (256 ** exp))
                exp = exp - 1
        return(intip)