导航

python学习笔记(1)

Posted on 2018-02-27 00:43  stumn  阅读(132)  评论(0)    收藏  举报

1.配置文件默认设置

settings>>Editor>>File and Code Templates

#!/user/bin/env python  ——环境配置,在cmd中使用默认的python环境
#-*- coding:utf-8 -*-   ——声明字符集(比如用于在python2.x中输入中文)
#Author:stumn           ——作者声明  

2.字符编码

path = "###"
with open (path, 'r') as text:
    words = text.read().split()
    print(words)
    for word in words:
        print("{}-{}times.".format(word, words.count(word)))

运行这段代码后会出现如下错误:

UnicodeDecodeError: 'gbk' codec can't decode byte 0xbf in position2:illegal multibyte sequence.

这是由编码引起的错误,经查阅资料,简述编码问题如下: GBK:2Bytes代表一个字符(满足中文)

Unicode:兼容万国语言,2Bytes代表一个字符(2**16 - 1 = 65536,即6万多个字符)——数字转换速度快,但是占用空间大

UTF-8:对因为使用1Bytes,对中文使用3Bytes(可变长度编码)

      ——对不同的字符适用不同的长度表示,精准并节省空间,但是每次都要计算出字符需要多长的Bytes才能准确表示,转换速度慢

1.内存中使用的编码是unicode,用空间换时间(程序都需要加载到内存中才能运行,因而内存应该是尽可能的保证快);

2.硬盘中或者网络传输使用utf-8, 网络I/O延迟或者磁盘I/O延迟要远大于utf-8的转换延迟,而且I/O应该是尽可能的节省宽带,保证数据传输的稳定性。

附字符编码的发展史

ASCII  255  1bytes

  > >1980  gb2312 7XXX

    >>1995  GBK1.0  2w+

      >>2000  GB18030  27XXX

    >>unicode  2bytes

      //utf-8  en:1bytes, ch:3bytes

这里的问题即是使用了错误的编码方式打开了文件。

那么,此处的程序问题有如下的解决方案

可以转换文件的编码方式,比如先以gbk格式读文件,再将其保存为另一个utf-8的文本,再读该文件。

制定打开的方式为 ‘gbk’ 或者编码范围更广的 ‘gb18030’,并且使用 ‘ignore’ 来忽略非法字符:

file = open(path, encoding='gb18030', errors='ignore')

或者:

file = open(path).read().decode('g18030', 'ignore')

 3.输出的三种格式

a.  %s的使用

informaton = "
-------infomation of %s-------
Name:%s
Age:%s
Job:%s
Saraly;%s
" %(name, name, age, job, salary)

b.  { }的使用一

informaton = "
-------infomation of {_name}-------
Name;{_name}
Age:{_age}
Job:{_job}
Saraly:{_saraly}
" .format(_name=name, _age=age, _job=job, _salary=salary)

c.  { }的使用二

informaton = "
-------infomation of {0}-------
Name;{0}
Age:{1}
Job:{2}
Saraly:{3}
" .format(name, age, job, salary)

尽量不要使用加号拼接,因为使用加号拼接会开辟很多内存,效率低下。