python常用模块

一、zip函数

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。

我们可以使用 list() 转换来输出列表。

如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

语法

zip 语法:

zip([iterable, ...])

参数说明:

  • iterabl -- 一个或多个迭代器;

返回值

返回元组列表

>>>a = [1,2,3] 
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 返回一个对象
>>> zipped <zip object at 0x103abc288>
>>> list(zipped) # list() 转换为列表 [(1, 4), (2, 5), (3, 6)]
>>> list(zip(a,c)) # 元素个数与最短的列表一致 [(1, 4), (2, 5), (3, 6)]
>>> a1, a2 = zip(*zip(a,b)) # 与 zip 相反,zip(*) 可理解为解压,返回二维矩阵式
>>> list(a1) [1, 2, 3]
>>> list(a2) [4, 5, 6] >>>

  二、struct打包模块                                                

 struct模块中最主要的三个函数式pack()、unpack()、calcsize()。

  •  pack(fmt, v1, v2, ...)  ------ 根据所给的fmt描述的格式将值v1,v2,...转换为一个字符串。
  •  unpack(fmt, bytes)    ------ 根据所给的fmt描述的格式将bytes反向解析出来,返回一个元组。
  •  calcsize(fmt)             ------ 根据所给的fmt描述的格式返回该结构的大小。
import struct

pack_num = struct.pack('i', 126)
print('pack_string',pack_num,len(pack_num))
unpack_num = struct.unpack('i', pack_num)
print('unpack_string',unpack_num)

# pack_string b'~\x00\x00\x00' 4
# unpack_string (126,)

print("len: ", struct.calcsize('i'))  # len:  4
print("len: ", struct.calcsize('ii'))   # len:  8
print("len: ", struct.calcsize('f'))    # len:  4
print("len: ", struct.calcsize('ff'))     # len:  8
print("len: ", struct.calcsize('s'))      # len:  1
print("len: ", struct.calcsize('ss'))      # len:  2
print("len: ", struct.calcsize('d'))     # len:  8
print("len: ", struct.calcsize('dd'))     # len:  16
print("len: ", struct.calcsize('B'))     # len:  1
print("len: ", struct.calcsize('!BH'))     # len:  3
print("len: ", struct.calcsize('!BQ'))     # len:  9

三、enumerate函数

enumerate()说明
enumerate()是python的内置函数。enumerate在字典上是枚举、列举的意思
对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值
enumerate多用于在for循环中得到计数
1.for循环
list = ["","","张亚飞"]
i = 0
for a in list:
    print(i,a)
    i += 1

for i,a in enumerate(list):
    print(i,a)
    
for i,a in enumerate(list,1):
    print(i,a)

2.读取文件

法一:
count = len(open('1.txt', 'rb').readlines())
法二:
count = 0
for index, line in enumerate(open('1.txt','rb')):
    count += 1

四、tqdm模块(打印进度条)

from tqdm import tqdm
import time
a=0
for i in tqdm(range(1,10)):
#    print(i)
#    print('哈哈')
    a += i
    time.sleep(0.1)
print(a)

五、jieba                                                                           

# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
"""
Created on Wed Aug 15 18:41:28 2018

@author: Zhang Yafei
"""
"""
jieba
“结巴”中文分词:做最好的 Python 中文分词组件
主要功能
1.分词
jieba.cut 方法接受三个输入参数: 需要分词的字符串;cut_all 参数用来控制是否采用全模式;HMM 参数用来控制是否使用 HMM 模型
jieba.cut_for_search 方法接受两个参数:需要分词的字符串;是否使用 HMM 模型。该方法适合用于搜索引擎构建倒排索引的分词,粒度比较细
待分词的字符串可以是 unicode 或 UTF-8 字符串、GBK 字符串。注意:不建议直接输入 GBK 字符串,可能无法预料地错误解码成 UTF-8
jieba.cut 以及 jieba.cut_for_search 返回的结构都是一个可迭代的 generator,可以使用 for 循环来获得分词后得到的每一个词语(unicode),或者用
jieba.lcut 以及 jieba.lcut_for_search 直接返回 list
jieba.Tokenizer(dictionary=DEFAULT_DICT) 新建自定义分词器,可用于同时使用不同词典。jieba.dt 为默认分词器,所有全局分词相关函数都是该分词器的映射。
"""
import sys
sys.path.insert(0,'D:/pytho3.6/Lib/site-packages')
import jieba

seg_list = jieba.cut("我来到北京清华大学", cut_all=True)#全模式
print('全模式:',list(seg_list))
seg_list = jieba.cut("我来到北京清华大学", cut_all=False)
print('精确模式:',list(seg_list))  # 精确模式
seg_list = jieba.cut("他来到了网易杭研大厦")  # 默认是精确模式
print('默认:',list(seg_list)) #(此处,“杭研”并没有在词典中,但是也被Viterbi算法识别出来了)
seg_list = jieba.cut_for_search("小明硕士毕业于中国科学院计算所,后在日本京都大学深造")  # 搜索引擎模式
print('搜索引擎:',list(seg_list))
"""
2.添加自定义词典
载入词典
开发者可以指定自己自定义的词典,以便包含 jieba 词库里没有的词。虽然 jieba 有新词识别能力,但是自行添加新词可以保证更高的正确率
用法: jieba.load_userdict(file_name) # file_name 为文件类对象或自定义词典的路径
词典格式和 dict.txt 一样,一个词占一行;每一行分三部分:词语、词频(可省略)、词性(可省略),用空格隔开,顺序不可颠倒。file_name 若为路径或二进制方式打开的文件,则文件必须为 UTF-8 编码。
词频省略时使用自动计算的能保证分出该词的词频。
"""
jieba.load_userdict("userdict.txt")
import jieba.posseg as pseg

jieba.add_word('石墨烯')
jieba.add_word('凱特琳')
jieba.del_word('自定义词')

test_sent = (
"李小福是创新办主任也是云计算方面的专家; 什么是八一双鹿\n"
"例如我输入一个带“韩玉赏鉴”的标题,在自定义词库中也增加了此词为N类\n"
"「台中」正確應該不會被切開。mac上可分出「石墨烯」;此時又可以分出來凱特琳了。"
)
words = jieba.cut(test_sent)
print('/'.join(words))

print("="*40)

result = pseg.cut(test_sent)

for w in result:
    print(w.word, "/", w.flag, ", ", end=' ')

print("\n" + "="*40)

terms = jieba.cut('easy_install is great')
print('/'.join(terms))
terms = jieba.cut('python 的正则表达式是好用的')
print('/'.join(terms))

print("="*40)
# test frequency tune
testlist = [
('今天天气不错', ('今天', '天气')),
('如果放到post中将出错。', ('', '')),
('我们中出了一个叛徒', ('', '')),
]

for sent, seg in testlist:
    print('/'.join(jieba.cut(sent, HMM=False)))
    word = ''.join(seg)
    print('%s Before: %s, After: %s' % (word, jieba.get_FREQ(word), jieba.suggest_freq(seg, True)))
    print('/'.join(jieba.cut(sent, HMM=False)))
    print("-"*40)
"""
调整词典
使用 add_word(word, freq=None, tag=None) 和 del_word(word) 可在程序中动态修改词典。
使用 suggest_freq(segment, tune=True) 可调节单个词语的词频,使其能(或不能)被分出来。
注意:自动计算的词频在使用 HMM 新词发现功能时可能无效。
"""
print('/'.join(jieba.cut('如果放到post中将出错。', HMM=False)))
jieba.suggest_freq(('', ''), True)
print('/'.join(jieba.cut('如果放到post中将出错。', HMM=False)))
print('/'.join(jieba.cut('「台中」正确应该不会被切开', HMM=False)))
jieba.suggest_freq('台中', True)
print('/'.join(jieba.cut('「台中」正确应该不会被切开', HMM=False)))
"""
3.关键词提取
    3.1基于 TF-IDF 算法的关键词抽取
import jieba.analyse
jieba.analyse.extract_tags(sentence, topK=20, withWeight=False, allowPOS=())
sentence 为待提取的文本
topK 为返回几个 TF/IDF 权重最大的关键词,默认值为 20
withWeight 为是否一并返回关键词权重值,默认值为 False
allowPOS 仅包括指定词性的词,默认值为空,即不筛选
jieba.analyse.TFIDF(idf_path=None) 新建 TFIDF 实例,idf_path 为 IDF 频率文件
代码示例 (关键词提取)
https://github.com/fxsjy/jieba/blob/master/test/extract_tags.py
"""
"""
关键词提取所使用逆向文件频率(IDF)文本语料库可以切换成自定义语料库的路径
用法: jieba.analyse.set_idf_path(file_name) # file_name为自定义语料库的路径
自定义语料库示例:https://github.com/fxsjy/jieba/blob/master/extra_dict/idf.txt.big
用法示例:https://github.com/fxsjy/jieba/blob/master/test/extract_tags_idfpath.py
"""
"""
关键词提取所使用停止词(Stop Words)文本语料库可以切换成自定义语料库的路径
用法: jieba.analyse.set_stop_words(file_name) # file_name为自定义语料库的路径
自定义语料库示例:https://github.com/fxsjy/jieba/blob/master/extra_dict/stop_words.txt
用法示例:https://github.com/fxsjy/jieba/blob/master/test/extract_tags_stop_words.py
"""
"""
关键词一并返回关键词权重值示例
用法示例:https://github.com/fxsjy/jieba/blob/master/test/extract_tags_with_weight.py
"""
"""
    3.2 基于 TextRank 算法的关键词抽取
jieba.analyse.textrank(sentence, topK=20, withWeight=False, allowPOS=('ns', 'n', 'vn', 'v')) 直接使用,接口相同,注意默认过滤词性。
jieba.analyse.TextRank() 新建自定义 TextRank 实例
算法论文: TextRank: Bringing Order into Texts

基本思想:
将待抽取关键词的文本进行分词
以固定窗口大小(默认为5,通过span属性调整),词之间的共现关系,构建图
计算图中节点的PageRank,注意是无向带权图
"""
"""
词性标注
jieba.posseg.POSTokenizer(tokenizer=None) 新建自定义分词器,tokenizer 参数可指定内部使用的 jieba.Tokenizer 分词器。jieba.posseg.dt 为默认词性标注分词器。
标注句子分词后每个词的词性,采用和 ictclas 兼容的标记法。
"""
用法示例
import jieba.posseg as pseg
words = pseg.cut("我爱北京天安门")
for word, flag in words:
    print('%s %s' % (word, flag))
原理:将目标文本按行分隔后,把各行文本分配到多个 Python 进程并行分词,然后归并结果,从而获得分词速度的可观提升
"""
5.并行分词
基于 python 自带的 multiprocessing 模块,目前暂不支持 Windows
用法:
jieba.enable_parallel(4) # 开启并行分词模式,参数为并行进程数
jieba.disable_parallel() # 关闭并行分词模式
例子:https://github.com/fxsjy/jieba/blob/master/test/parallel/test_file.py
实验结果:在 4 核 3.4GHz Linux 机器上,对金庸全集进行精确分词,获得了 1MB/s 的速度,是单进程版的 3.3 倍。
注意:并行分词仅支持默认分词器 jieba.dt 和 jieba.posseg.dt。
"""
6.Tokenize:返回词语在原文的起止位置
注意,输入参数只接受 unicode
默认模式
result = jieba.tokenize(u'永和服装饰品有限公司')
for tk in result:
    print("word %s\t\t start: %d \t\t end:%d" % (tk[0],tk[1],tk[2]))
word 永和                start: 0                end:2
word 服装                start: 2                end:4
word 饰品                start: 4                end:6
word 有限公司            start: 6                end:10

搜索模式
result = jieba.tokenize(u'永和服装饰品有限公司', mode='search')
for tk in result:
    print("word %s\t\t start: %d \t\t end:%d" % (tk[0],tk[1],tk[2]))
word 永和                start: 0                end:2
word 服装                start: 2                end:4
word 饰品                start: 4                end:6
word 有限                start: 6                end:8
word 公司                start: 8                end:10
word 有限公司            start: 6                end:10
7.ChineseAnalyzer for Whoosh 搜索引擎
引用: from jieba.analyse import ChineseAnalyzer
用法示例:https://github.com/fxsjy/jieba/blob/master/test/test_whoosh.py
8.命令行分词
使用示例:python -m jieba news.txt > cut_result.txt

命令行选项(翻译):

使用: python -m jieba [options] filename

结巴命令行界面。

固定参数:
  filename              输入文件

可选参数:
  -h, --help            显示此帮助信息并退出
  -d [DELIM], --delimiter [DELIM]
                        使用 DELIM 分隔词语,而不是用默认的' / '。
                        若不指定 DELIM,则使用一个空格分隔。
  -p [DELIM], --pos [DELIM]
                        启用词性标注;如果指定 DELIM,词语和词性之间
                        用它分隔,否则用 _ 分隔
  -D DICT, --dict DICT  使用 DICT 代替默认词典
  -u USER_DICT, --user-dict USER_DICT
                        使用 USER_DICT 作为附加词典,与默认词典或自定义词典配合使用
  -a, --cut-all         全模式分词(不支持词性标注)
  -n, --no-hmm          不使用隐含马尔可夫模型
  -q, --quiet           不输出载入信息到 STDERR
  -V, --version         显示版本信息并退出

如果没有指定文件名,则使用标准输入。
--help 选项输出:

$> python -m jieba --help
Jieba command line interface.

positional arguments:
  filename              input file

optional arguments:
  -h, --help            show this help message and exit
  -d [DELIM], --delimiter [DELIM]
                        use DELIM instead of ' / ' for word delimiter; or a
                        space if it is used without DELIM
  -p [DELIM], --pos [DELIM]
                        enable POS tagging; if DELIM is specified, use DELIM
                        instead of '_' for POS delimiter
  -D DICT, --dict DICT  use DICT as dictionary
  -u USER_DICT, --user-dict USER_DICT
                        use USER_DICT together with the default dictionary or
                        DICT (if specified)
  -a, --cut-all         full pattern cutting (ignored with POS tagging)
  -n, --no-hmm          don't use the Hidden Markov Model
  -q, --quiet           don't print loading messages to stderr
  -V, --version         show program's version number and exit

If no filename specified, use STDIN instead.
延迟加载机制
jieba 采用延迟加载,import jieba 和 jieba.Tokenizer() 不会立即触发词典的加载,一旦有必要才开始加载词典构建前缀字典。如果你想手工初始 jieba,也可以手动初始化。

import jieba
jieba.initialize()  # 手动初始化(可选)
在 0.28 之前的版本是不能指定主词典的路径的,有了延迟加载机制后,你可以改变主词典的路径:

jieba.set_dictionary('data/dict.txt.big')
jieba

  详情请见githup地址 结巴中文分词

六、you-get                                                                     

# -*- coding: utf-8 -*-
"""
Created on Mon Aug 13 19:32:18 2018

@author: Zhang Yafei
"""
https://github.com/soimort/you-get
入门
下载视频
当您获得感兴趣的视频时,您可能希望使用--info/ -i选项查看所有可用的质量和格式:

$ you-get -i 'https://www.youtube.com/watch?v=jNQXAC9IVRw'
$ you-get 'https://www.youtube.com/watch?v=jNQXAC9IVRw'
$ you-get --itag=18 'https://www.youtube.com/watch?v=jNQXAC9IVRw'
$ you-get https://stallman.org/rms.jpg
$ you-get http://kopasas.tumblr.com/post/69361932517
$ you-get "Richard Stallman eats"
暂停并恢复下载
您可以使用Ctrl+ C来中断下载。
临时.download文件保存在输出目录中。下次you-get使用相同的参数运行时,下载进度将从上一个会话恢复。如果文件被完全下载(临时.download扩展已经消失),you-get将跳过下载。
要强制重新下载,请使用--force/ -f选项。(警告:这样做会覆盖任何具有相同名称的现有文件或临时文件!)
设置下载文件的路径和名称
$ you-get -o ~/Videos -O zoo.webm 'https://www.youtube.com/watch?v=jNQXAC9IVRw'
提示:
如果您遇到默认视频节目的问题,这些选项很有用,这些视频节目可能包含与您当前的shell /操作系统/文件系统不兼容的特殊字符。
如果您编写脚本以批量下载文件并将其放入具有指定名称的指定文件夹中,这些选项也很有用。
代理设置
$ you-get -x 127.0.0.1:8087 'https://www.youtube.com/watch?v=jNQXAC9IVRw'
但是,http_proxy默认情况下应用系统代理设置(即环境变量)。要禁用任何代理,请使用该--no-proxy选项。
提示:
如果你需要使用代理了很多(如果您的网络阻止某些网站),你可能希望使用you-get与proxychains和设置alias you-get="proxychains -q you-get"(Bash中)。
对于某些网站(例如优酷网),如果您需要访问仅在中国大陆可用的视频,可以选择使用特定代理从网站提取视频信息:--extractor-proxy/ -y。
观看视频
使用--player/ -p选项将视频输入您选择的媒体播放器,例如mplayer或vlc,而不是下载它:
$ you-get -p vlc 'https://www.youtube.com/watch?v=jNQXAC9IVRw'
或者,如果您希望在浏览器中观看视频,则无需广告或评论部分:
$ you-get -p chromium 'https://www.youtube.com/watch?v=jNQXAC9IVRw'
提示:
可以使用该-p选项来启动另一个下载管理器,例如you-get -p uget-gtk 'https://www.youtube.com/watch?v=jNQXAC9IVRw',尽管它们可能不能很好地一起播放。
加载cookie
并非所有视频都可供所有人公开使用。如果您需要登录您的帐户以访问某些内容(例如,私人视频),则无法you-get通过--cookies/ -c选项提供浏览器Cookie 。

注意:

截至目前,我们支持两种格式的浏览器cookie:Mozilla cookies.sqlite和Netscape cookies.txt。
重用提取的数据
使用--url/ -u获取从页面中提取的可下载资源URL列表。使用--json得到提取的数据的抽象JSON格式。

警告:

从目前来看,这一功能已不被稳定和JSON模式可能会在未来的重大更改。
支持的网站
现场    网址    影片?    图片?    特刊?
YouTube的    https://www.youtube.com/    ✓        
推特    https://twitter.com/    ✓    ✓    
VK    http://vk.com/    ✓    ✓    
藤蔓    https://vine.co/    ✓        
Vimeo的    https://vimeo.com/    ✓        
Vidto    http://vidto.me/    ✓        
Videomega    http://videomega.tv/    ✓        
优酷    http://www.veoh.com/    ✓        
tumblr    https://www.tumblr.com/    ✓    ✓    ✓
TED    http://www.ted.com/    ✓        
的SoundCloud    https://soundcloud.com/            ✓
展厅    https://www.showroom-live.com/    ✓        
Pinterest的    https://www.pinterest.com/        ✓    
MusicPlayOn    http://en.musicplayon.com/    ✓        
MTV81    http://www.mtv81.com/    ✓        
Mixcloud    https://www.mixcloud.com/            ✓
优酷    http://www.metacafe.com/    ✓        
Magisto    http://www.magisto.com/    ✓        
可汗学院    https://www.khanacademy.org/    ✓        
互联网档案    https://archive.org/    ✓        
Instagram的    https://instagram.com/    ✓    ✓    
InfoQ中文站    http://www.infoq.com/presentations/    ✓        
Imgur    http://imgur.com/        ✓    
重音乐档案    http://www.heavy-music.ru/            ✓
Google+的    https://plus.google.com/    ✓    ✓    
Freesound上    http://www.freesound.org/            ✓
Flickr的    https://www.flickr.com/    ✓    ✓    
FC2视频    http://video.fc2.com/    ✓        
Facebook的    https://www.facebook.com/    ✓        
eHow    http://www.ehow.com/    ✓        
位DailyMotion    http://www.dailymotion.com/    ✓        
Coub    http://coub.com/    ✓        
CBS    http://www.cbs.com/    ✓        
乐队夏令营    http://bandcamp.com/            ✓
AliveThai    http://alive.in.th/    ✓        
interest.me    http://ch.interest.me/tvn    ✓        
755 
ナナゴーゴー    http://7gogo.jp/    ✓    ✓    
NICONICO 
ニコニコ动画    http://www.nicovideo.jp/163 
网易视频
网易云音乐    http://v.163.com/ 
http://music.163.com/    ✓        ✓
56网    http://www.56.com/    ✓        
ACFUN    http://www.acfun.tv/    ✓        
百度
百度贴吧    http://tieba.baidu.com/    ✓    ✓    
爆米花网    http://www.baomihua.com/    ✓        
bilibili 
哔哩哔哩    http://www.bilibili.com/    ✓        
Dilidili    http://www.dilidili.com/    ✓        
豆瓣    http://www.douban.com/    ✓        ✓
斗鱼    http://www.douyutv.com/    ✓        
熊猫
熊猫    http://www.panda.tv/    ✓        
凤凰视频    http://v.ifeng.com/    ✓        
风行网    http://www.fun.tv/    ✓        
爱奇艺
爱奇艺    http://www.iqiyi.com/    ✓        
激动网    http://www.joy.cn/    ✓        
酷6网    http://www.ku6.com/    ✓        
酷狗音乐    http://www.kugou.com/            ✓
酷我音乐    http://www.kuwo.cn/            ✓
乐视网    http://www.le.com/    ✓        
荔枝FM    http://www.lizhi.fm/            ✓
秒拍    http://www.miaopai.com/    ✓        
MioMio弹幕网    http://www.miomio.tv/    ✓        
痞客邦    https://www.pixnet.net/    ✓        
PPTV聚力    http://www.pptv.com/    ✓        
齐鲁网    http://v.iqilu.com/    ✓        
QQ 
腾讯视频    http://v.qq.com/    ✓        
企鹅直播    http://live.qq.com/    ✓        
新浪
新浪视频
微博秒拍视频    http://video.sina.com.cn/ 
http://video.weibo.com/    ✓        
搜狐
搜狐视频    http://tv.sohu.com/    ✓        
土豆网
土豆    http://www.tudou.com/    ✓        
虾米    http://www.xiami.com/    ✓        ✓
阳光卫视    http://www.isuntv.com/    ✓        
音悦台    http://www.yinyuetai.com/    ✓        
优酷网
优酷    http://www.youku.com/    ✓        
战旗电视    http://www.zhanqi.tv/lives    ✓        
央视网    http://www.cntv.cn/    ✓        
花瓣    http://huaban.com/        ✓    
Naver 
네이버    http://tvcast.naver.com/    ✓        
芒果TV    http://www.mgtv.com/    ✓        
火猫电视    http://www.huomao.com/    ✓        
全民直播    http://www.quanmin.tv/    ✓        
阳光宽频网    http://www.365yg.com/    ✓        
西瓜视频    https://www.ixigua.com/    ✓        
快手    https://www.kuaishou.com/    ✓    ✓    
抖音    https://www.douyin.com/    ✓        
中国体育(TV)    http://v.zhibo.tv/ 
http://video.zhibo.tv/    ✓        
对于不在列表中的所有其他站点,通用提取器将负责从页面中查找和下载有趣的资源。
you-get视频下载

  详情请见githup地址 you-get

七、wget网络文件下载神器                                             

# -*- coding: utf-8 -*-

"""
@Datetime: 2018/12/13
@Author: Zhang Yafei
"""
import wget

DATA_URL = 'https://img.3ajiepai.com/data/attachment/forum/201812/04/102501eopses2zvpskpab1.jpg'

out_fname = 'jiepai.jpg'

wget.download(DATA_URL, out=out_fname)

 八、optparse

       optparse,是一个更够让程序设计人员轻松设计出简单明了、易于使用、符合标准的Unix命令例程式的Python模块。生成使用和帮助信息

       首先你必须导入该类,并创建一个OptionParser对象,然后再使用parser.add_option(...)待定义命令行参数,及其帮助文档。

        每个命令行参数就是由参数名字符串和参数属性组成的。如 -f 或者 file 分别是长短参数名:

# -*- coding: utf-8 -*-

"""
@Datetime: 2018/12/17
@Author: Zhang Yafei
"""
from optparse import OptionParser

optParser = OptionParser()
optParser.add_option('-i', '--infile', action='store', type="string", dest='filename')
optParser.add_option("-o", "--outfile", action="store", dest="outfile",
                     default='', help="make lots of noise [default]")
# optParser.parse_args() 剖析并返回一个字典和列表,
# 字典中的关键字是我们所有的add_option()函数中的dest参数值,
# 而对应的value值,是add_option()函数中的default的参数或者是
# 由用户传入optParser.parse_args()的参数
fakeArgs = ['-i', 'file.txt', '-o', 'how.csv', 'arg1', 'arg2']
option, args = optParser.parse_args()
op, ar = optParser.parse_args(fakeArgs)
print("option : ", option)
print("args : ", args)
print("op : ", op)
print("ar : ", ar)
E:\python\my_package>python _optparse.py -i file1 -o file2 arg1 arg2
option :  {'filename': 'file1', 'outfile': 'file2'}
args :  ['arg1', 'arg2']
op :  {'filename': 'file.txt', 'outfile': 'how.csv'}
ar :  ['arg1', 'arg2'] 
add_option()参数说明:
        action:存储方式,分为三种store、store_false、store_true
        type:类型
        dest:存储的变量
        default:默认值
        help:帮助信息
    # The set of actions that involve storing a value somewhere;
    # also listed just for constructor argument validation.  (If
    # the action is one of these, there must be a destination.)
    STORE_ACTIONS = ("store",
                     "store_const",
                     "store_true",
                     "store_false",
                     "append",
                     "append_const",
                     "count")
action 

 action的取值有那么多,我着重说三个store、store_false、store_true 三个取值。 action默认取值store。
       --store 上表示命令行参数的值保存在options对象中。例如上面一段代码,如果我们对optParser.parse_args()函数传入的参数列表中带有‘-f’,那么就会将列表中‘-f’的下一个元素作为其dest的实参filename的值,他们两个参数形成一个字典中的一个元素{filename:file_txt}。相反当我们的参数列表中没有‘-f’这个元素时,那么filename的值就会为空。

      --store_false fakeArgs 中存在'-v'verbose将会返回False,而不是‘how are you’,也就是说verbose的值与'-v'的后一位无关,只与‘-v’存在不存在有关。

      --store_ture  这与action="store_false"类似,只有其中有参数'-v'存在,则verbose的值为True,如果'-v'不存在,那么verbose的值为None。

optParser.add_option("-f","--file",action = "store",type = "string",dest = "fileName")

optParser.add_option("-v","--vison", action="store", dest="verbose",default='gggggg',

                     help="make lots of noise [default]")
help

主要用于显示帮助信息,使用optParser.print_help()将帮助栏显示出来。

 九、itertools模块

# -*- coding: utf-8 -*-

"""
Datetime: 2020/06/25
Author: Zhang Yafei
Description: itertools 包
为高效循环而创建迭代器的函数
本模块实现一系列 iterator ,这些迭代器受到APL,Haskell和SML的启发。为了适用于Python,它们都被重新写过。
本模块标准化了一个快速、高效利用内存的核心工具集,这些工具本身或组合都很有用。它们一起形成了“迭代器代数”,这使得在纯Python中有可能创建简洁又高效的专用工具。
例如,SML有一个制表工具: tabulate(f),它可产生一个序列 f(0), f(1), ...。在Python中可以组合 map() 和 count() 实现: map(f, count())。
这些内置工具同时也能很好地与 operator 模块中的高效函数配合使用。例如,我们可以将两个向量的点积映射到乘法运算符: sum(map(operator.mul, vector1, vector2)) 。
"""


def itertools_count():
    """
    无穷的迭代器  count(start,[step])
    count 接受两个参数
        start:循环开始的数字
        step:循环中的间隔
    """
    from itertools import count
    c = count(0, 2)
    v = next(c)
    while v < 10:
        v = next(c)
        print(v, end=',')


def itertools_cycle():
    """
    无穷迭代器 cycle()
    cycle就是一while True,无限循环里面的数字。
    """
    from itertools import cycle

    c = cycle('ABCD')
    for i in range(10):
        print(next(c), end=',')


def itertools_repeat():
    """
    repeat(elem,[n])
    重复迭代elem,n次
    """
    from itertools import repeat

    r = repeat(1, 3)
    for i in range(3):
        print(next(r), end=',')


def itertools_accumulate():
    """
    迭代器 accumulate()
    accumulate(p,[func])
    使用func的函数对迭代对象p进行累积。
    """
    from itertools import accumulate

    test_list = [i for i in range(1, 11)]
    for i in accumulate(test_list):  # 默认是operator.add
        print(i, end=',')
    print()
    for i in accumulate(test_list, lambda x, y: x * y):  # operator.mul
        print(i, end=',')


def itertools_chain():
    """
    迭代器 chain()
    chain()中可以放多个迭代对象,然后一一迭代出来。
    """
    from itertools import chain

    ch = chain([1, 2, 3], {4: 4, 5: 5}, {6, 7, 8}, (9,), [10, [11, 12]])
    for i in ch:
        print(i)


def itertools_chain_from_iterable():
    """
    迭代器 chain.from_iterable()
    跟chain不同的地方在于:
        chain: 可以接受多个迭代对象
        chain.from_iterable():可以接受一个可以产生迭代对象的迭代器
    """
    from itertools import chain

    def gen_iterables():
        for i in range(10):
            yield range(i)

    for i in chain.from_iterable(gen_iterables()):
        print(i)


def itertools_compress():
    """
    迭代器 compress
    compress(data, selectors)
    这是就是看下这个就知道了s是selectors中的元素。
    (d[0] if s[0]), (d[1] if s[1]), ...
    """
    from itertools import compress

    print(list(compress(['A', 'B', 'C', 'D'], [0, 1, 1, 1])))


def itertools_dropwhile():
    """
    迭代器 dropwhile()
    dropwhile(pred, seq)
    循环开始的条件是,直到遇到第一次不满足pred条件的情况,才开始遍历。
    """
    from itertools import dropwhile

    l = [1, 7, 6, 3, 8, 2, 10]
    print(list(dropwhile(lambda x: x < 3, l)))


def itertools_groupby():
    """
    groupby
    这个感觉有点像sql中的group_by。可以对字符串,列表等进行分组。
    返回键和,组里的内容
    """
    from itertools import groupby
    # 对字符串进行分组
    for k, g in groupby('11111234567'):
        print(k, list(g))
    d = {1: 1, 2: 2, 3: 2}
    # 按照字典value来进行分组
    for k, g in groupby(d, lambda x: d.get(x)):
        print(k, list(g))


def itertools_slice():
    """
    islice
    这个就是对迭代对象进行切割,不支持负数,有点像range(1, 10, 2)
    """
    from itertools import islice
    print(list(islice('ABCDEFG', 2, 3, None)))


def itertools_zip_longest():
    """
    zip_longest
    这个和zip很像,不同地方在于:
    zip结束取决于里面最短的迭代对象
    zip_longest结束取决于里面最长的迭代对象
    :return:
    """

    from itertools import zip_longest

    for x, y in zip_longest([1, 2, 3], [1, 2]):
        print(x, y)
    for x, y in zip([1, 2, 3], [1, 2]):
        print(x, y)


def itertools_product():
    """
    product
    相当于 嵌套的for
    排列组合迭代器 product 嵌套的for
    """
    from itertools import product
    for i, j in product([1, 2, 3], [4, 5]):
        print(i, j)


def itertools_permutations():
    """
    全排列,比如输出123的全部情况。(1,2,3),(1,3,2)…
    """
    from itertools import permutations
    print(list(permutations('123')))


def itertools_combinations():
    """
    combinations(p,r)
    从p中找出所有长度为r的排列情况… 有顺序
    :return:
    """
    from itertools import combinations
    print(list(combinations([1, 2, 3], 2)))
    print(list(combinations('ABCD', 2)))


def itertools_combinations_with_replacement():
    """combinations_with_replacement()
    从p中找出所有长度为r的排列情况,有顺序,但包括自身就是会重复的意思。
    """
    from itertools import combinations_with_replacement
    print(list(combinations_with_replacement('ABCD', 2)))
    # AA AB AC AD BB BC BD CC CD DD


if __name__ == '__main__':
    itertools_count()
    itertools_cycle()
    itertools_repeat()
    itertools_accumulate()
    itertools_chain()
    itertools_chain_from_iterable()
    itertools_compress()
    itertools_dropwhile()
    itertools_groupby()
    itertools_slice()
    itertools_zip_longest()
    itertools_product()
    itertools_combinations()
    itertools_combinations_with_replacement()
    itertools_permutations()

十、collection模块

"""
namedtuple是一个函数,它用来创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。
这样一来,我们用namedtuple可以很方便地定义一种数据类型,它具备tuple的不变性,又可以根据属性来引用,使用十分方便。
"""
from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p.x)
print(p.y)

Circle = namedtuple('Circle', ['x', 'y', 'r'])

"""
deque
使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢了,因为list是线性存储,数据量大的时候,插入和删除效率很低。
deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈:
"""
from collections import deque

q = deque(['a', 'b', 'c'])
q.append('x')
q.appendleft('y')
print(q)

"""
defaultdict
使用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值,就可以用defaultdict:
"""
from collections import defaultdict

dd = defaultdict(lambda: 'N/A')
dd['key1'] = 'abc'
dd['key1']  # key1存在
dd['key2']  # key2不存在,返回默认值

"""
OrderedDict
使用dict时,Key是无序的。在对dict做迭代时,我们无法确定Key的顺序。
如果要保持Key的顺序,可以用OrderedDict:
"""
from collections import OrderedDict

d = dict([('a', 1), ('b', 2), ('c', 3)])
d  # dict的Key是无序的
od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
print(od)  # OrderedDict的Key是有序的
# 注意,OrderedDict的Key会按照插入的顺序排列,不是Key本身排序:

"""
Counter
Counter是一个简单的计数器,例如,统计字符出现的个数:
"""
from collections import Counter

c = Counter('programming')
print(c)

 

posted @ 2018-11-27 11:28  DreamBoy_张亚飞  阅读(414)  评论(0编辑  收藏  举报