Python学习笔记(五)Demos

来源:互联网 发布:tb程序化交易模型源码 编辑:程序博客网 时间:2024/05/20 01:09

生成随机串

import string,randomfield = string.letters + string.digitsdef getRandom():    return "".join(random.sample(field,4))def concatenate(group):    return "-".join([getRandom() for i in range(group)])if __name__ == '__main__'    print concatenate(4)

range()的作用是生成一个列表,range(10) =>0,1,2,3,4,5,6,7,8,9
其中最后一句,这个python文件什么时候是main呢?自己单独执行的时候是main,如果不是自己单独执行,name就为该python的文件名了。

统计单词

# -*- coding: utf-8 -*-import refrom collections import CounterFILESOURCE = "H:/pythonworkspace/yesterday once more.txt"'''yesterday once more'''def getMostCommonWord(articlefilesource):    '''输入一个英文的文件,统计其中单词出现的个数'''    pattern = r'''[A-Za-z]+|\$?\d+%?$'''    with open(articlefilesource) as f:        r = re.findall(pattern,f.read())        print r        print '*'*20        return Counter(r).most_common()if __name__ == '__main__':    print getMostCommonWord(FILESOURCE)

这里写图片描述
with as功能
使语法变得简练美观,还包括异常处理功能。要求with后面的函数包含一个
enter()函数和一个 exit()函数exit(self, type, value, trace
)有三个参数,用来异常处理,在执行sample.do_something()前,执行enter() ,执行后执行exit()

统计多个文件的词频

#coding:utf-8import re,osfrom collections import CounterFILE_PATH='H:/pythonworkspace'def getCounter(articlefilesource):    pattern = r'''[A-Za-z]+|\$?\d+%?$'''    with open(articlefilesource) as f:        r=re.findall(pattern,f.read())        return Counter(r)#过滤词stop_word=['the','in','of']def run(FILE_PATH):    #切换到目标所在目录    os.chdir(FILE_PATH)    #遍历该目录下的txt目录    total_counter = Counter()    for i in os.listdir(os.getcwd()):        if os.path.splitext(i)[1] == '.txt':            total_counter += getCounter(i)    #排除stopword    for l in stop_word:        total_counter[l] = 0    print total_counter.most_common()[0][0]if __name__ == '__main__':    run(FILE_PATH)

Counter返回的是一个键值对的 hasmap类型,Counter[key]可以获取统计结果。两个Counter相加,对应key value相加。
total_counter.most_common()是
这里写图片描述
total_counter.most_common()[0]=>(‘they’, 9)
total_counter.most_common()[0][0]=>they

由一条正则表达式引发的思考

pattern = r”’[A-Za-z]+|$?\d+%?$”’

if 后面跟的是条件表达式,条件表达式的结果为True或者False。
(1)如果if后面的条件是数字,只要这个数字不是0,python都会把它当做True处理,见下面的例子:
if 3:
print ‘OK’
输出OK,但是如果数字是0,就会被认为是False。
(2)如果if后面跟的是字符串,则只要这个字符串不为空串,python就把它看作True,参见下例
if ‘hehe’:
print ‘No problem’
No problem 就会被输出。

图片批量改尺寸

#encoding=utf-8from PIL import Imageimport osinputpath='H:/pythonworkspace/image/'outputpath= 'H:/pythonworkspace/image_processed/'def processImage(filesource,destsource,name,imgtype):    '''    filesource是存放待转换图片的目录    destsource是存放输出后转换的目录    name是文件名    imgtype文件类型    '''    imgtype='jpeg' if imgtype =='.jpg' else '.png'    im = Image.open(filesource + name)    rate = max(im.size[0]/640.0 if im.size[0]>640 else 0,im.size[1]/1136.0 if im.size[1]>1136 else 0)    print rate    if rate:        im.thumbnail((im.size[0]/rate,im.size[1]/rate))        print destsource+name    im.save(destsource+name,imgtype)def run():    os.chdir(inputpath)    for i in os.listdir(os.getcwd()):        postfix = os.path.splitext(i)[1]        if postfix == '.jpg' or  postfix == '.png':            processImage(inputpath,outputpath,i,postfix)run()

分解文件名的扩展名dir.splitext() =>(‘文件名’,’.后缀名’)
python支持这种语法
x,y,z=10,20,30,类似于C语言的结构体赋值
列表不允许赋值

import sys  reload(sys)  sys.setdefaultencoding('utf8')

setdefaultencoding时,之前要reload。

[random.choice(string.letters) for _ in range(4)]
由于_可以作为变量名,可以直接__

原创粉丝点击