Python一些代码记录

这个坑完全是为了记录Python数据处理中一些需要记一下的代码,随时补充。仔细想想,我的Python写的真是丑啊。

#把两个长度一样的数组x,y组合成一个(x,y)的数组
z=zip(x,y)
#map和reduce真的很有用的两个函数
isTradeble=map(lambda a,b:np.logical_and(a,b),
                  isTradeble==1,
                  [i>0 and np.isnan(i)==False for i in pb])
                  
condition=reduce(lambda a,b:np.logical_and(a,b),
                    [np.isnan(cps)==False,
                    np.isnan(openEx[-1])==False,
                    np.isnan(stockListIndex)==0])
#axis=0就是纵向切片,axis=1是横向切片
MA3=np.sum(closePrice[-3:],axis=0)/3

#axis=0是竖着拼接,axis=1是横着拼接
SWIndexQuote=np.append(tmp1,tmp2,axis=1)

#rolling()是一个很有用的函数,意思就是滚动出来一个窗口的意思
MA3=cum_close.rolling(3).mean()
#method有很多种方法,ffill的意思是向前填充,也就是遇到空置,填充它前面的值
pd.replace(np.nan,method='ffill',inplace=True)
#numpy中切片操作传出来的是view而不是副本,需要副本的话要用copy()
>>> a=np.array([1,2,3,4])
>>> b=a[:2]
>>> a
array([1, 2, 3, 4])
>>> b
array([1, 2])
>>> b[0]=3
>>> b
array([3, 2])
>>> a
array([3, 2, 3, 4])
#and这个操作符虽然可以用来做True和False的比较,但是用的时候需要小心
>>> 'a' and 'b'
'b'
#也就是说如果两个一样,返回的是同一个值;
#如果不一样,返回的是最右边第一个不一样的值(其实就是最右边的值啦)
#所以当使用list做and操作的时候要格外小心
>>> [False,False] and [True,True]
[True, True]
#对于np.array可以直接用&来操作
>>> np.array([False,False])&np.array([True,True])
array([False, False], dtype=bool)
#所以对于矩阵,可以直接用reduce做下来。
2016/9/12 posted in  Python
 

Datetime in Python and pandas

这几天由于工作所需,处理了一下Python的时间相关的对象和函数,做个小笔记。

2016/9/12 posted in  Python
 

记一次毫无意义的爬虫经历

前段时间觉得MAC的桌面背景看的有点腻了,于是想要去搞几张BG,搜了一下DOTA的主题,发现了这个比较不错的系列。

RUBICK GRAND MAGUS

作者是SHERON1030,网站上还有很多别的可以拿来做背景的图,很不错。
但是他的图库一张纸下载起来很麻烦,而我也没有找到什么打包的途径,于是考虑写个爬虫来爬。
本来之前从来没有写过爬虫,况且Python也是刚刚学了几天,那就边写边学吧!

import urllib2
import re

def downImage(address):
    path ='/Users/LiSheng/PycharmProjects/untitled'
    url = address
    p=re.compile('dota_2[\S]*')
    n=address.split('/')[2].split('.')[0]
    nameString=p.findall(url)
    name ='/Users/LiSheng/PycharmProjects/untitled/'+n+'_'+nameString[0]
    print name
    user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
    headers = {'User-Agent': user_agent}
    req = urllib2.Request(url, headers)
    conn=urllib2.urlopen(url)
    f = open(name,'wb+')
    f.write(conn.read())
    f.close()
    print(nameString[0]+' download finish!')
    
imageList=[]

def addImage(address):
    file=open('/Users/LiSheng/PycharmProjects/untitled/imageAddress.txt','a')
    file.write(address+'\n')
    imageList.append(address)

def openAddress(address):
    response=urllib2.urlopen(address)
    frontPage=response.read()
    unicodePage=frontPage.decode('utf-8')
    pattern =re.compile(r'\"http://[\S]*.deviantart.com/art/Dota-2-[\S]*\"')
    urls=pattern.findall(unicodePage)

    for url in urls:
        url=url[1:url.__len__()-1]
        newResponse=urllib2.urlopen(url)
        newPage=newResponse.read()
        newUnicodePage=newPage.decode('utf-8')
        pattern =re.compile(r'<img collect_rid="[\S]*" src="[\S]*.jpg"')
        imageURL=pattern.findall(newUnicodePage)
        for i in imageURL:
            x=i.split()
            xsrc=x[2][5:x[2].__len__()-1]
            #downImage(xsrc)
            print(xsrc)
            addImage(xsrc)

url2='http://sheron1030.deviantart.com/gallery/?offset=24'
url3='http://sheron1030.deviantart.com/gallery/?offset=48'

openAddress('http://sheron1030.deviantart.com/gallery/')
openAddress(url2)
openAddress(url3)

仅以此纪念我第一次好好写的Python代码与爬虫。最后不得不说,由于学校网络爆炸,跑起来之后BOOM SHAKALAKA,运行了几次,没有以此可以顺利爬完的,pity。

尽管任务没有完成,但是非常高兴地复习了一下正则表达式。

你问我为什么把这么丑的代码贴上来?
那是为了让博客显得不呢么空啊兄弟啊!

2016/9/6 posted in  Python