bianle
11/19/2015 - 2:13 PM

python 趣味

python 趣味

import re,urllib

aa="http://dict.youdao.com/search?tab=chn&keyfrom=dict.top&q="
print ("input q! to exit ")
while 1:
    word=raw_input(">>>")
    if word=="q!":
        exit()
    else:
        word=word.replace(' ','+')
        url=aa+word
        s=urllib.urlopen(url).read()
        comm=re.compile(r'<td class="dttitle2"><font color="#013694"><b>(.*?)<\/b><\/font><\/td>')
        tem=comm.findall(s)
        com=re.compile('<td class="attributem1web">(.*?)</td>',re.S|re.M|re.I)
        result=com.findall(s)
    if  tem:
        for i in tem:
            temp=i.decode('utf8').encode('cp936')
            print (temp)
            print '\n'
    else:
        print ("no such word\n") 
# -*- coding: utf-8 -*-
import sqlite3
print ("input q! to exit ")
while 1:
    word=raw_input(">>>").decode('gbk').encode('utf-8')
    if word=="q!":
        exit()
    else:
        cx = sqlite3.connect("wubi.db")
        sql = "select * from wb where character like '"+word+"%' "
        cu=cx.cursor()
        print sql
        cu.execute(sql)
        for item in cu.fetchall():
            for element in item:
                print element,
            print


import re
import json
import urllib
import base64
import hashlib
import requests


WBCLIENT = 'ssologin.js(v.1.3.18)'
sha1 = lambda x: hashlib.sha1(x).hexdigest()



def wblogin(username, password):
    session = requests.Session()

#        headers={
 #           'User-Agent': 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHT'
  #                        'ML, like Gecko) Chrome/21.0.1180.89 Safari/537.1'
   #     }
    #)
    resp = session.get(
        'http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sina'
        'SSOController.preloginCallBack&su=%s&client=%s' %
        (base64.b64encode(username), WBCLIENT)
    )
    pre_login_str = re.match(r'[^{]+({.+?})', resp.content).group(1)
    pre_login_json = json.loads(pre_login_str)
    data = {
        'entry': 'weibo',
        'gateway': 1,
        'from': '',
        'savestate': 7,
        'useticket': 1,
        'ssosimplelogin': 1,
        'su': base64.b64encode(urllib.quote(username)),
        'service': 'miniblog',
        'servertime': pre_login_json['servertime'],
        'nonce': pre_login_json['nonce'],
        'pcid': pre_login_json['pcid'],
        'vsnf': 1,
        'vsnval': '',
        'pwencode': 'wsse',
        'sp': sha1(sha1(sha1(password)) +
                   str(pre_login_json['servertime']) +
                   pre_login_json['nonce']),
        'encoding': 'UTF-8',
        'url': 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.si'
               'naSSOController.feedBackUrlCallBack',
        'returntype': 'META'
    }
    resp = session.post(
        'http://login.sina.com.cn/sso/login.php?client=%s' % WBCLIENT,
        data=data
    )
    login_url = re.search(r'replace\([\"\']([^\'\"]+)[\"\']',
                          resp.content).group(1)
    resp = session.get(login_url)
    login_str = re.match(r'[^{]+({.+?}})', resp.content).group(1)
    return session, json.loads(login_str)


if __name__ == '__main__':
    from pprint import pprint
    session, login_info = wblogin('1401494@uc.cn', 'xxx')
    uid = login_info['userinfo']['uniqueid']
    url = "http://weibo.com/u/"+uid
    resp = session.get(url)
    #print resp.content
import random

print sorted(random.sample(range(1, 34), 6)), ':', random.randrange(1, 17)

def chinese_zodiac(year):  
     return u'猴鸡狗猪鼠牛虎兔龙蛇马羊'[year%12]  
  
def zodiac(month, day):  
    n = (u'摩羯座',u'水瓶座',u'双鱼座',u'白羊座',u'金牛座',u'双子座',u'巨蟹座',u'狮子座',u'处女座',u'天秤座',u'天蝎座',u'射手座')  
    d = ((1,20),(2,19),(3,21),(4,21),(5,21),(6,22),(7,23),(8,23),(9,23),(10,23),(11,23),(12,23))  
    return n[len(filter(lambda y:y<=(month,day), d))%12]  
#! /bin/env python
# -*- coding: utf-8 -*-

'''
A python script to visualize your social network of renren.
Inspired by:
http://www.voidspace.org.uk/python/articles/urllib2.shtml
http://www.voidspace.org.uk/python/articles/cookielib.shtml
http://blog.csdn.net/lkkang/article/details/7362888
http://cos.name/2011/04/exploring-renren-social-network/
'''

import urllib
import urllib2
import cookielib
import re
import cPickle as p
import networkx as nx
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']

__author__ = """Reverland (lhtlyy@gmail.com)"""

# Control parameters,EDIT it here
## Login
username = 'None'
password = 'None'
## Control Graphs, Edit for better graphs as you need
label_flag = True # Whether shows labels.NOTE: configure your matplotlibrc for Chinese characters.
remove_isolated = True # Whether remove isolated nodes(less than iso_level connects)
different_size = True # Nodes for different size, bigger means more shared friends
iso_level = 10
node_size = 40 # Default node size


def login(username, password):
    """log in and return uid"""
    logpage = "http://www.renren.com/ajaxLogin/login"
    data = {'email': username, 'password': password}
    login_data = urllib.urlencode(data)
    cj = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    urllib2.install_opener(opener)
    res = opener.open(logpage, login_data)
    print "Login now ..."
    html = res.read()
    #print html

    # Get uid
    print "Getting user id of you now"
    res = urllib2.urlopen("http://www.renren.com/home")
    html = res.read()
    # print html
    uid = re.search("'ruid':'(\d+)'", html).group(1)
    # print uid
    print "Login and got uid successfully"
    return uid


def getfriends(uid):
    """Get the uid's friends and return the dict with uid as key,name as value."""
    print "Get %s 's friend list" % str(uid)
    pagenum = 0
    dict1 = {}
    while True:
        targetpage = "http://friend.renren.com/GetFriendList.do?curpage=" + str(pagenum) + "&id=" + str(uid)
        res = urllib2.urlopen(targetpage)
        html = res.read()

        pattern = '<a href="http://www\.renren\.com/profile\.do\?id=(\d+)"><img src="[\S]*" alt="[\S]*[\s]\((.*)\)" />'

        m = re.findall(pattern, html)
        #print len(m)
        if len(m) == 0:
            break
        for i in range(0, len(m)):
            no = m[i][0]
            uname = m[i][1]
            #print uname, no
            dict1[no] = uname
        pagenum += 1
    print "Got %s 's friends list successfully." % str(uid)
    return dict1


def getdict(uid):
    """cache dict of uid in the disk."""
    try:
        with open(str(uid) + '.txt', 'r') as f:
            dict_uid = p.load(f)
    except:
        with open(str(uid) + '.txt', 'w') as f:
            p.dump(getfriends(uid), f)
        dict_uid = getdict(uid)
    return dict_uid


def getrelations(uid1, uid2):
    """receive two user id, If they are friends, return 1, otherwise 0."""
    dict_uid1 = getdict(uid1)
    if uid2 in dict_uid1:
        return 1
    else:
        return 0


def getgraph(username, password):
    """Get the Graph Object and return it.
You must specify a Chinese font such as `SimHei` in ~/.matplotlib/matplotlibrc"""
    uid = login(username, password)
    dict_root = getdict(uid) # Get root tree

    G = nx.Graph() # Create a Graph object
    for uid1, uname1 in dict_root.items():
        # Encode Chinese characters for matplotlib **IMPORTANT**
        # if you want to draw Chinese labels,
        uname1 = unicode(uname1, 'utf8')
        G.add_node(uname1)
        for uid2, uname2 in dict_root.items():
            uname2 = unicode(uname2, 'utf8')
            # Not necessary for networkx
            if uid2 == uid1:
                continue
            if getrelations(uid1, uid2):
                G.add_edge(uname1, uname2)

    return G


def draw_graph(username, password, filename='graph.txt', label_flag=True, remove_isolated=True, different_size=True, iso_level=10, node_size=40):
    """Reading data from file and draw the graph.If not exists, create the file and re-scratch data from net"""
    print "Generating graph..."
    try:
        with open(filename, 'r') as f:
            G = p.load(f)
    except:
        G = getgraph(username, password)
        with open(filename, 'w') as f:
            p.dump(G, f)
    #nx.draw(G)
    # Judge whether remove the isolated point from graph
    if remove_isolated is True:
        H = nx.empty_graph()
        for SG in nx.connected_component_subgraphs(G):
            if SG.number_of_nodes() > iso_level:
                H = nx.union(SG, H)
        G = H
    # Ajust graph for better presentation
    if different_size is True:
        L = nx.degree(G)
        G.dot_size = {}
        for k, v in L.items():
            G.dot_size[k] = v
        node_size = [G.dot_size[v] * 10 for v in G]
    pos = nx.spring_layout(G, iterations=50)
    nx.draw_networkx_edges(G, pos, alpha=0.2)
    nx.draw_networkx_nodes(G, pos, node_size=node_size, node_color='r', alpha=0.3)
    # Judge whether shows label
    if label_flag is True:
        nx.draw_networkx_labels(G, pos, alpha=0.5)
    #nx.draw_graphviz(G)
    plt.show()

    return G

if __name__ == "__main__":
    G = draw_graph("le5u@w.cn", "xxxxxx")
#coding=utf-8

import urllib2
import httplib2
import re
import random
from encryption import QQmd5
import cookielib
import requests
import getpass
import time
import json

import urllib
class webqq:
    def __init__(self, user, pwd):
        self.cookies = cookielib.CookieJar()
        self.opener = urllib2.build_opener(
                urllib2.HTTPHandler(),
                urllib2.HTTPSHandler(),
                urllib2.HTTPCookieProcessor(self.cookies),
                )
        urllib2.install_opener(self.opener)
        self.user = user
        self.pwd = pwd
        self.mycookie = ";"
        #self.clientid = "21485768"
        #self.clientid = "34592990"
        self.clientid = str(random.randint(10000000, 99999999))

    def getSafeCode(self):
        url = 'https://ssl.ptlogin2.qq.com/check?uin=' + str(self.user) + '&appid=1003903&js_ver=10017&js_type=0&login_sig=0ihp3t5ghfoonssle-98x9hy4uaqmpvu*8*odgl5vyerelcb8fk-y3ts6c3*7e8-&u1=http%3A%2F%2Fweb2.qq.com%2Floginproxy.html&r=0.8210972726810724'
        req = urllib2.Request(url)
        #self.mycookie += "confirmuin=" + self.user + ";"
        #req.add_header('Cookie', self.mycookie)
        req  = urllib2.urlopen(req)
        #cs = ['%s=%s' %  (c.name, c.value) for c in self.cookies]
        #self.mycookie += ";".join(cs)
        verifycode = re.search(r"'(\d)','(.+)','(.+)'", req.read())
        self.check = verifycode.group(1)
        self.verifycode1 = verifycode.group(2)
        self.verifycode2 = verifycode.group(3)
        if self.check == "1":
            url = 'https://ssl.captcha.qq.com/getimage?&uin='+str(self.user)+'&aid=1002101&0.45644426648505' + str(random.randint(10,99))
            req = urllib2.Request(url)
            req = urllib2.urlopen(req)
            self.fi = open("./image.jgp", "wb")
            while 1:
                c = req.read()
                if not c:
                    break
                else :self.fi.write(c)
            self.fi.close()
            self.verifycode1 = raw_input("verifer:")
        print self.check, self.verifycode1, self.verifycode2

    def loginGet(self):
        #cs = ['%s=%s' %  (c.name, c.value) for c in self.cookies]
        #self.mycookie += ";" "; ".join(cs)

        login_url = 'https://ssl.ptlogin2.qq.com/login?u='+self.user +'&p=' + str(QQmd5().md5_2(self.pwd, self.verifycode1, self.verifycode2)) + '&verifycode=' + self.verifycode1 + '&webqq_type=10&remember_uin=1&login2qq=1&aid=1003903&u1=http%3A%2F%2Fweb.qq.com%2Floginproxy.html%3Flogin2qq%3D1%26webqq_type%3D10&h=1&ptredirect=0&ptlang=2052&from_ui=1&pttype=1&dumy=&fp=loginerroralert&action=2-14-32487&mibao_css=m_webqq&t=1&g=1&js_type=0&js_ver=10015&login_sig=0ihp3t5ghfoonssle-98x9hy4uaqmpvu*8*odgl5vyerelcb8fk-y3ts6c3*7e8-'

        req = urllib2.Request(login_url)
        req.add_header("Referer", "https://ui.ptlogin2.qq.com/cgi-bin/login?target=self&style=5&mibao_css=m_webqq&appid=1003903&enable_qlogin=0&no_verifyimg=1&s_url=http%3A%2F%2Fweb.qq.com%2Floginproxy.html&f_url=loginerroralert&strong_login=1&login_state=10&t=20121029001")

        #req.add_header("Cookie", self.mycookie)
        #self.opener.addheaders.append(("Cookie", self.mycookie))
        req = urllib2.urlopen(req)
        print req.read()
        for cookie in self.cookies:
            print cookie.name, ":",  cookie.value
            if cookie.name == 'ptwebqq':
                self.ptwebqq = cookie.value

        print urllib2.urlopen('http://web2.qq.com/web2/get_msg_tip?uin=&tp=1&id=0&retype=1&rc=0&lv=3&t=1358252543124').read()
        #cs = ['%s=%s' %  (c.name, c.value) for c in self.cookies]
        #self.mycookie += ";" "; ".join(cs)

    def loginPost(self):
        url = 'http://d.web2.qq.com/channel/login2'
        data = 'r=%7B%22status%22%3A%22online%22%2C%22ptwebqq%22%3A%22' + self.ptwebqq + '%22%2C%22passwd_sig%22%3A%22%22%2C%22clientid%22%3A%22'+self.clientid+'%22%2C%22psessionid%22%3Anull%7D&clientid='+self.clientid+'&psessionid=null'
        req = urllib2.Request(url, data)
        #req.add_header('Cookie', self.mycookie)
        req.add_header('Referer', 'http://d.web2.qq.com/proxy.html?v=20110331002&callback=1&id=2')
        req = urllib2.urlopen(req)
        self.result = json.load(req)
        print self.result['result']['vfwebqq'], self.result['result']['psessionid']

    def getGroupList(self):
        url = 'http://s.web2.qq.com/api/get_group_name_list_mask2'
        data = 'r=%7B%22vfwebqq%22%3A%22'+self.result['result']['vfwebqq'] +'%22%7D'
        req = urllib2.Request(url, data)
        req.add_header('Referer', 'http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=1')
        req = urllib2.urlopen(req)
        self.group = json.load(req)
        pass

    def getFriend(self):
        url = 'http://s.web2.qq.com/api/get_user_friends2'
        data = 'r=%7B%22vfwebqq%22%3A%22'+self.result['result']['vfwebqq'] +'%22%7D'
        req = urllib2.Request(url, data)
        req.add_header('Referer', 'http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=1')
        req = urllib2.urlopen(req)
        self.friend = json.load(req)
        print self.friend
        pass

    def getMeg(self):
        print urllib2.urlopen('http://web2.qq.com/web2/get_msg_tip?uin=&tp=1&id=0&retype=1&rc=0&lv=3&t=1358252543124').read()
        pass

    def poll2(self):
        url = 'http://d.web2.qq.com/channel/poll2'
        data ='r=%7B%22clientid%22%3A%22'+self.clientid+'%22%2C%22psessionid%22%3A%22'+self.result['result']['psessionid']+'%22%2C%22key%22%3A0%2C%22ids%22%3A%5B%5D%7D&clientid='+self.clientid+'&psessionid='+self.result['result']['psessionid']
        req = urllib2.Request(url, data)
        #req.add_header('Cookie', self.mycookie)
        req.add_header('Referer', 'http://d.web2.qq.com/proxy.html?v=20110331002&callback=1&id=3')
        result = json.load(urllib2.urlopen(req))
        print result


    def sendMsg(self, uin, msg):
        url = 'http://d.web2.qq.com/channel/send_buddy_msg2'
        data = 'r=%7B%22to%22%3A'+uin+'%2C%22face%22%3A237%2C%22content'+urllib.quote(r'":"[\"'+msg+r'\",\"\\n【提示:此用户正在使用shift webQq】\",[\"font\",{\"name\":\"宋体\",\"size\":\"10\",\"style\":[0,0,0],\"color\":\"000000\"}]]","')+'msg_id%22%3A13190001%2C%22clientid%22%3A%22'+self.clientid+'%22%2C%22psessionid%22%3A%22'+self.result['result']['psessionid']+'%22%7D&clientid='+self.clientid+'&psessionid='+self.result['result']['psessionid']
        req = urllib2.Request(url, data)
        #req.add_header('Cookie', self.mycookie)
        req.add_header('Referer', 'http://d.web2.qq.com/proxy.html?v=20110331002&callback=1&id=2')
        print urllib2.urlopen(req).read()
        pass

    def sendQunMsg(self, uin, msg):
        url = 'http://d.web2.qq.com/channel/send_qun_msg2'
        data = 'r=%7B%22group_uin%22%3A'+uin+'%2C%22face%22%3A237%2C%22content'+urllib.quote(r'":"[\"'+msg+r'\",\"\\n【提示:此用户正在使用shift webQq】\",[\"font\",{\"name\":\"宋体\",\"size\":\"10\",\"style\":[0,0,0],\"color\":\"000000\"}]]","')+'msg_id%22%3A13190001%2C%22clientid%22%3A%22'+self.clientid+'%22%2C%22psessionid%22%3A%22'+self.result['result']['psessionid']+'%22%7D&clientid='+self.clientid+'&psessionid='+self.result['result']['psessionid']
        req = urllib2.Request(url, data)
        req.add_header('Referer', 'http://d.web2.qq.com/proxy.html?v=20110331002&callback=1&id=2')
        print urllib2.urlopen(req).read()
        pass

def main():
    user = raw_input('QQ:')
    pwd = getpass.getpass('password: ')
    qq = webqq(user, pwd)
    qq.getSafeCode()
    qq.loginGet()
    qq.loginPost()
    qq.getGroupList()
    qq.getFriend()
    while 0:
        time.sleep(0.5)
        qq.poll2()
    for i in range(100):
        print 'to', qq.friend['result']['info'][0]['uin']
        print 'to', qq.group['result']['gnamelist'][10]
        #qq.sendMsg(str(qq.friend['result']['info'][0]['uin']), 'clientjsfzhiyong')
        ms = ''
        for _ in xrange(i):
            ms += '。'
        qq.sendQunMsg(str(qq.group['result']['gnamelist'][10]['gid']), ms)
        #qq.sendMsg('2236071402', 'geisf')

if __name__ == "__main__":
    main()
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
 
def implicitplot3d(fn, bbox=(-1.5,1.5)):
    xmin, xmax, ymin, ymax, zmin, zmax = bbox*3
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    A = np.linspace(xmin, xmax, 50)
    B = np.linspace(xmin, xmax, 20)
    A1,A2 = np.meshgrid(A,A)
    for z in B:
        X,Y = A1,A2
        Z = fn(X,Y,z)
        cset = ax.contour(X, Y, Z+z, [z], zdir='z')
    for y in B:
        X,Z = A1,A2
        Y = fn(X,y,Z)
        cset = ax.contour(X, Y+y, Z, [y], zdir='y')
    for x in B:
        Y,Z = A1,A2
        X = fn(x,Y,Z)
        cset = ax.contour(X+x, Y, Z, [x], zdir='x')
    ax.set_zlim3d(zmin,zmax)
    ax.set_xlim3d(xmin,xmax)
    ax.set_ylim3d(ymin,ymax)
    plt.show()
 
implicitplot3d(lambda x,y,z: (x*x + 2*y*y + z*z -1)**3 - x*x*z*z*z - y*y*z*z*z/10.)
# -*- coding: gbk -*-
"""名称:猜数字
规则:系统自动生成一个不包含重复数字的四位数整数,在提示符下玩家输入一个不包含重复数字的四位数整数,根据系统提示调整输入,最终猜出目标数字。
提示:2对3有,说明刚输入的数字中有3个数包含在目标数字中,且有2个数字位置也正确。
命令:
***输入1000:重来一局。
***输入1111:跳关。
***输入9999:退出程序。
"""
import random

__author__='EU软件工作室'

def isRepeat(s):
    '''检查参数是否包含重复数字'''
    b=False
    w1=s//1000
    w2=(s-w1*1000)//100
    w3=(s-w1*1000-w2*100)//10
    w4=s-w1*1000-w2*100-w3*10
    if w1==w2 or w1==w3 or w1==w4 or w2==w3 or w2==w4 or w3==w4:
        b=True
    return b
            
def getTarget():
    '''获得一个不含重复数字的四位数整数.'''
    random.seed
    t=random.randint(1023,9876)
    while isRepeat(t):
        t=random.randint(1023,9876)
    return t

if __name__=='__main__':

    run=True
    target=0
    level=1
    gCount=0

    print(__doc__)

    while run:
        if target==0:
            target=getTarget()
            print('第%d关!!目标数字已经创建:xxxx(4位整数,1023-9876)。\n' % level)
            continue
        
        gCount+=1
        print("第%d次:" % gCount,)
        sguess=input('请输入:')
        sguess=sguess.strip()
        while sguess=="" or sguess.isnumeric()==False or len(str(int(sguess)))!=4 or len(sguess)!=4 or isRepeat(int(sguess))==True:
            if sguess=='1000':
                print("\n\n目标数字是%d,重新开始第%d关。" % (target,level))
                target=0
                gCount=0
                break
            elif sguess=='1111':
                print('\n跳关无耻!目标数字是%d。' % target)
                target=0
                gCount=0
                level+=1
                break
            elif sguess=='9999':
                print('\n取消游戏,本次共闯过%d关。' % (level-1))
                run=False
                break
            else:
                sguess=input('非法内容,重新输入:')
        if run==False:
            break
        if sguess=='1111':
            continue
        guess=int(sguess)            
        if guess==target:
            print("猜对了!!目标数字正是%d,共%d次完成,第%d关通过。\n" % (target,gCount,level))
            level+=1
            target=0
            gCount=0
        elif guess in range(1023,9876):
            i=0
            you=0
            dui=0
            sguess=str(guess)
            starget=str(target)
            while i<4:
                if sguess[i] in starget:
                    you+=1
                    if sguess[i]==starget[i]:
                        dui+=1
                i+=1    
            print("%d,%d对%d有。\n" % (guess,dui,you))
            
    print("运行结束。")
print '\n'.join([' '.join(['%s*%s=%-2s' % (y,x,x*y) for y in range(1,x+1)]) for x in range(1,10)])