Python2

Python2&Python3

2017-05-29  本文已影响0人  Epiphanyyaoyao

1、Python2中urllib和urllib2模块是相关分开的,各自执行不同的功能,但是在Python3中urllib和urllib2模块合并了

2、# coding=utf-8 linux下编辑器的编码格式为utf-8,而python的默认编译格式为gbk,因此需要指定编译格式为utf-8。

汉字作为变量值,默认为GBK编码,需要指定为unicode,使用 u'汉字' 。

字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。

decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码。

encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码。

csv文件存储格式为ascill格式,因此linux下保存cvs格式还会报错。一种方式是将csv人为转换为utf-8格式,在csv文件头部写入utf-8编码:

import codecs

csvfile.write(codecs.BOM_UTF8)

另一种方式是在编译器头部添加:

import sys

reload(sys)

sys.setdefaultencoding('utf-8')

3、写入csv

import csv

csvfile=file('csvtest.csv','wb')

writer=csv.writer(csvfile)

writer.writerow(['id','url','keywords'])

writer.wrtierows(list)

csvfile.close()

4、Python可以定义类

class boy:

gender='male'

interest='girl'

def say(self):

return 'i am a boy'

用法和java完全一致。

5、easy_install 和 pip的介绍:

easy_install和pip都是用来下载安装Python一个公共资源库PyPI

的相关资源包的,pip是easy_install的改进版,提供更好的提示信

息,删除package等功能。老版本的python中只有easy_install,

没有pip。

easy_install 打包和发布 Python 包

pip 是包管理

easy_install的用法:

安装一个包

easy_install 包名

easy_install "包名 == 包的版本号"

升级一个包

easy_install -U "包名 >= 包的版本号"

pip 的用法

安装一个包

pip install 包名

pip install 包名 == 包的版本号

升级一个包(如果不提供version号,升级到最新版本)

pip install --upgrade 包名 >= 包的版本号

删除一个包

pip uninstall  包名

6、写入csv文件

import csv

csvfile = file('csv_test.csv', 'wb')

writer = csv.writer(csvfile)

writer.writerow(['姓名', '年龄', '电话'])

data = [

('小河', '25', '1234567'),

('小芳', '18', '789456')

]

writer.writerows(data)

csvfile.close()

7、将excel中的日期转换为python中的日期

xlrd.xldate.xldate_as_datetime(data[0][0].value,0)

上一篇下一篇

猜你喜欢

热点阅读