Python语法资料汇总

1、python2转python3
python2和python3语法互不兼容!!!
还好python提供了工具!
要转换一个文件夹及其子文件夹中的文件,只需要一句话:
cmd中输入:
python  pythong安装目录/Scripts/2to3-script.py -w  要转的文件夹名称
#例如python  E:/Anaconda3/Scripts/2to3-script.py -w assignment1py3
#其中assignment1py3为文件夹!

其中  -w  表示转换完了写回到原文件,,所以执行前最好是复制一个副本出来
如果要转的文件不是以.py结尾的,,则需要一个个文件去敲代码,比如
python  E:/Anaconda3/Scripts/2to3-script.py -w knn.ipynb



2、python入门资料
cs231n的python介绍: http://cs231n.github.io/python-numpy-tutorial/

Numpy for Matlab users: https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html
numpy推荐直接用ANACONDA套装: https://www.continuum.io/downloads


3、python文件处理
缓存的大小可以在open时设置:
http://stackoverflow.com/questions/3167494/how-often-does-python-flush-to-a-file
示例代码如下:
def processFileLineByLine(filename,outfilename, lineFunc, headLineFunc=None,encoding='utf-8'):
    '''
    将filename中的每一行通过lineFunc转换后输出到outfilename文件中,
    如果对首行有特殊的处理需求,可以设置headLineFunc
    '''
    import codecs
    f = codecs.open(filename, 'r', encoding);
    fo = codecs.open(outfilename, 'w', encoding,buffering=1024*1024);
    if(headLineFunc!=None):
        fo.write(headLineFunc(f.readline()));
        
    while True:
        lines=f.readlines(2048);
        if(not lines or len(lines)==0):
            break;
        for line in lines:
            fo.write(lineFunc(line));
    f.close();
    fo.close();
def changeSplitChar2(filename,outfilename,encoding='utf-8',oldSplitChar='\t',newSplitChar=','): 
    def chchar(line):
        return line.replace(oldSplitChar,newSplitChar);
    processFileLineByLine(filename, outfilename, lineFunc=chchar, encoding=encoding)



4、iterator & generator
参见: http://anandology.com/python-practice-book/iterators.html
generator 是 iterator 的简化版(代码量减少),本质完全相同。
generator以函数形式编写,, 代码运行到 yield x 时输出一个x ,,相当于next(it);
注意:  python3中采用  next(it) , 而非 it.next()的形式;

可以采用 list(it)  生成list

5、python 函数的default value是共享的
http://stackoverflow.com/questions/4841782/python-constructor-and-default-value
http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument
http://effbot.org/zone/default-values.htm
def append(i,a=None):
    if(a is None): a=list()
    a.append(i);
    return a;

# a 在def语句执行时初始化,所以是共享的。。。。。
def append_Wrong(i,a=[]):
    a.append(i)
    return a;

if __name__ == '__main__': 
    print(append(1))  #[1]
    print(append(2))  #[2]
    
    print(append_Wrong(1))  #[1]
    print(append_Wrong(2))  #[1, 2]    


6、列出所有变量
参见 http://stackoverflow.com/questions/633127/viewing-all-defined-variables
  • vars() 列出所有变量,为一个dict,  for varName, varValue in vars().items()...
  • dir() 列出所有变量名, 之后可以通过eval(variableName) 来获取变量
  • globals() 全局变量
  • locals() 局部变量


6、python2 的ascii’ codec can’t encode
通过以下语句修改全局设置,参见(内容很详细): http://in355hz.iteye.com/blog/1860787
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

虽然那篇博文中不推荐这么做,但我觉着这个方案没什么不好的,比较utf-8是兼容ascii的,既然原本为ascii的编解码器,那么换为utf-8的编解码器应该没任何问题。

7、python命令行环境变量设置
  • PYTHONIOENCODING=UTF-8 python ***.py  #更改编码
  • export PYTHONPATH=$PYTHONPATH:newpath/subfolder  #增加库路径

猜你喜欢

转载自cherishlc.iteye.com/blog/2300576