<0088pj>OG网吧游戏平台软件件里的筹是啥意思?

&p&按照我的入门路径整理了一下,同时进行了一些优化,给大家做个分享。&/p&&p&先做个简单说明,自己写个简单爬虫是一件非常非常容易的事情,有足够的耐心连一周时间都不用就可以入门。照这篇文章练习,不出一个月你就可以非常熟练的使用各种爬虫。一点都不会错。&/p&&h2&基础知识体系&/h2&&p&很多人推荐书本资料,但是对于一个简单爬虫的使用者来说,书籍资料学习起来很慢,成本太高。不如从网上找写经典的资料看一下。&/p&&p&1.&a href=&//link.zhihu.com/?target=http%3A//blog.csdn.net/column/details/why-bug.html& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&专栏:Python爬虫入门教程 - 请叫我汪海&i class=&icon-external&&&/i&&/a&&/p&&p&CSDN阅读量第一的爬虫专栏,创作于2014年。对于爬虫基础知识的介绍非常到位,尽管由于年代久远部分案例代码已经无法使用,但是对于新手建立自己的爬虫基础知识非常有用。&/p&&p&2.&a href=&//link.zhihu.com/?target=http%3A//blog.csdn.net/column/details/eastmount-spider.html%3F%26page%3D1& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&专栏:Python爬虫之Selenium+Phantomjs+CasperJS - Eastmount&i class=&icon-external&&&/i&&/a&&/p&&p&CSDN阅读量第二的爬虫专栏,作者一直在持续更新。最近的一篇文章发布于今年4月。相对于请叫我汪海的教程,这篇文章的在建立体系方面稍弱,但是案例和教程也非常经典。&/p&&p&3.&a href=&//link.zhihu.com/?target=http%3A//blog.csdn.net/column/details/python3-spider.html& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&专栏:Python3爬虫之路 - fly_yr&i class=&icon-external&&&/i&&/a&&/p&&p&基于Python3的爬虫实例。&/p&&p&4.&a href=&//link.zhihu.com/?target=http%3A//blog.csdn.net/column/details/15504.html& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&专栏:分布式爬虫原理与实现 - HAPPENgft&i class=&icon-external&&&/i&&/a&&/p&&p&分布式爬虫的基础原理,值得一读。&/p&&h2&实战项目练习&/h2&&p&搭建了基本的知识体系,接下来就是应该实战了。&/p&&p&按照基本的练习过程,豆瓣、知乎等等是练习爬虫的重灾区。&/p&&p&不过现在就独立进行爬取还有点勉强,可以通过相应教程来进行锻炼。&/p&&p&(鉴于我入门练习的案例比较散乱,这里借用 &a class=&member_mention& href=&//www.zhihu.com/people/eaf435b228ce0b038a4afe& data-hash=&eaf435b228ce0b038a4afe& data-hovercard=&p$b$eaf435b228ce0b038a4afe&&@路人甲&/a& 大神介绍过的几个案例)&/p&&blockquote&1. &a href=&//link.zhihu.com/?target=http%3A//cuiqingcai.com/990.html& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Python爬虫实战一之爬取糗事百科段子&i class=&icon-external&&&/i&&/a&&br&2. &a href=&//link.zhihu.com/?target=http%3A//cuiqingcai.com/993.html& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Python爬虫实战二之爬取百度贴吧帖子&i class=&icon-external&&&/i&&/a&&br&3. &a href=&//link.zhihu.com/?target=http%3A//cuiqingcai.com/2083.html& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Python爬虫实战三之实现山东大学无线网络掉线自动重连&i class=&icon-external&&&/i&&/a&&br&4. &a href=&//link.zhihu.com/?target=http%3A//cuiqingcai.com/1001.html& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Python爬虫实战四之抓取淘宝MM照片&i class=&icon-external&&&/i&&/a&&br&5. &a href=&//link.zhihu.com/?target=http%3A//cuiqingcai.com/1076.html& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Python爬虫实战五之模拟登录淘宝并获取所有订单&i class=&icon-external&&&/i&&/a&&br&6. &a href=&//link.zhihu.com/?target=http%3A//cuiqingcai.com/1972.html& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Python爬虫实战六之抓取爱问知识人问题并保存至数据库&i class=&icon-external&&&/i&&/a&&br&7. &a href=&//link.zhihu.com/?target=http%3A//cuiqingcai.com/997.html& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Python爬虫实战七之计算大学本学期绩点&i class=&icon-external&&&/i&&/a&&br&8. &a href=&//link.zhihu.com/?target=http%3A//cuiqingcai.com/2852.html& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Python爬虫实战八之利用Selenium抓取淘宝匿名旺旺&i class=&icon-external&&&/i&&/a&&/blockquote&&h2&知识深化&/h2&&p&练习过以上几个案例之后,你应该已经有相当的实战能力了。不过想要搞定所有网站还是有点难。这个阶段我的建议是了解一下常用的爬虫工具——&b&注意不是全部,是常用,同时是了解,不是精通。&/b&&/p&&p&1.&a href=&//link.zhihu.com/?target=https%3A//github.com/scrapy/scrapy& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&scrapy/scrapy&i class=&icon-external&&&/i&&/a&&/p&&p&2.&a href=&//link.zhihu.com/?target=https%3A//www.crummy.com/software/BeautifulSoup/& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Beautiful Soup&i class=&icon-external&&&/i&&/a&&/p&&p&3.&a href=&//link.zhihu.com/?target=https%3A//docs.python.org/2/library/urllib2.html& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&urllib2&i class=&icon-external&&&/i&&/a&(其实这个超简单了...)&/p&&p&4.&a href=&//link.zhihu.com/?target=http%3A//phantomjs.org/& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&PhantomJS&i class=&icon-external&&&/i&&/a&&/p&&p&5.&a href=&//link.zhihu.com/?target=http%3A//casperjs.org/& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&CasperJS&i class=&icon-external&&&/i&&/a&&/p&&p&6.&a href=&//link.zhihu.com/?target=http%3A//docs.seleniumhq.org/& class=& external& target=&_blank& rel=&nofollow noreferrer&&&span class=&invisible&&http://&/span&&span class=&visible&&docs.seleniumhq.org/&/span&&span class=&invisible&&&/span&&i class=&icon-external&&&/i&&/a&&/p&&p&搞定这几个之后,我相信你已经是一个非常不错的爬虫高手了。&/p&&h2&坚持!&/h2&&p&与所有技能的学习一样,爬虫的学习最重要的不是天分,而是坚持。&/p&&p&我是怎么坚持下来的呢?之前的回答提过一下,这次也搬过来给大家看看吧,免得大家再找了。&/p&&p&比如我学爬虫的动力是什么呢?因为偶尔看到的一篇文章。&/p&&p&&br&&/p&&figure&&img src=&https://pic1.zhimg.com/v2-e3eaa84ce020ae_b.png& data-caption=&& data-size=&normal& data-rawwidth=&800& data-rawheight=&719& class=&origin_image zh-lightbox-thumb& width=&800& data-original=&https://pic1.zhimg.com/v2-e3eaa84ce020ae_r.png&&&/figure&&p&为了给题主更多的动力,我决定贡献出这篇文章: &a href=&//link.zhihu.com/?target=http%3A//blog.csdn.net/baidu_/article/details/& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Python爬虫之——爬取妹子图片&i class=&icon-external&&&/i&&/a& &/p&&p&&b&以下内容来自上述链接,版权归作者所有。&/b&&/p&&figure&&img src=&https://pic4.zhimg.com/v2-a769cf8ed41ccd785ec680bdfc9e8b67_b.png& data-caption=&& data-size=&normal& data-rawwidth=&480& data-rawheight=&480& class=&origin_image zh-lightbox-thumb& width=&480& data-original=&https://pic4.zhimg.com/v2-a769cf8ed41ccd785ec680bdfc9e8b67_r.png&&&/figure&&p&&br&&/p&&h2&环境:python 3.6&/h2&&p&注:单线程版以在&a href=&//link.zhihu.com/?target=http%3A//lib.csdn.net/base/android& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&安卓&i class=&icon-external&&&/i&&/a&的Qpython(py2.7)上运行成功&/p&&h2&第三方库&/h2&&p&requests:解析url &br&beautifulsoup4:不会正则表达式童鞋的福音,可以容易的提取到html文件中各种标签及其属性&/p&&h2&安装方法: &/h2&&p&pip install requests &br&pip install beautifulsoup4&/p&&p&如果有错误请自行解决&/p&&h2&目标&/h2&&p&&a href=&//link.zhihu.com/?target=http%3A//mzitu.com/& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&http://mzitu.com&i class=&icon-external&&&/i&&/a& &br&话说回来,我半年前就开始学习py爬虫,但当时应该是兴趣不足,导致半途而废,所以说兴趣非常重要,我们的目标应该可以使大家有很大的兴趣,激励自己学习爬虫。&/p&&h2&原理&/h2&&p&学习爬虫,首先是要学习它的原理。打开网址(为了防止和谐我就不上图了 ),大家可以发现,一共有141页,每页都有很多套图,如果要你手动去保存,怎么操作?我想应该是这样,从第一页开始,点进第一个套图,然后保存每张图片,然后进行第二个套图……第一页完了之后第二页,从第一个套图开始,保存保存……这就是原理,当然,虽然这样能达到这个目的,但大家应该没有那么多的时间,那么我们就来学习爬虫,来替我们保存图片。&/p&&h2&步骤&/h2&&p&&b&1.获取网页源码&/b&&/p&&p&用浏览器的F12可以看到网页的源码,但我们现在要用Python这样做。&/p&&div class=&highlight&&&pre&&code class=&language-text&&#coding=utf-8
import requests
url = 'http://www.mzitu.com'
#设置headers,网站会根据这个判断你的浏览器及操作系统,很多网站没有此信息将拒绝你访问
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0. UBrowser/6.1. Safari/537.36'}
#用get方法打开url并发送headers
html = requests.get(url,headers = header)
#打印结果 .text是打印出文本信息即源码
print(html.text)
&/code&&/pre&&/div&&p&如果没问题的话结果会是这样类似&/p&&div class=&highlight&&&pre&&code class=&language-text&&......
$(&#index_banner_load&).find(&div&).appendTo(&#index_banner&);
$(&#index_banner&).css(&height&, 90);
$(&#index_banner_load&).remove();
&/code&&/pre&&/div&&p&这些就是网页的源码了。&/p&&p&&b&2.寻找所需信息&/b&&/p&&p&切换浏览器,右键‘查看网页源代码’,可以发现有很多这样的信息&/p&&div class=&highlight&&&pre&&code class=&language-text&&&li&&a href=&http://www.mzitu.com/89334& target=&_blank&&&img width='236' height='354' class='lazy' alt='我是标题我是标题我是标题我是标题我是标题我是标题' src='http://i.meizitu.net/pfiles/img/lazy.png' data-original='http://i.meizitu.net/thumbs/34_02b06_236.jpg' /&&/a&&span&&a href=&http://www.mzitu.com/89334& target=&_blank&&我是标题我是标题我是标题我是标题我是标题我是标题我是标题我是标题我是标题我是标题&/a&&/span&&span class=&time&&&/span&&span class=&view&&6,788次&/span&&/li&11
&/code&&/pre&&/div&&p&那么我们只需要提取这些东西就可以了…but:我写不出这么复杂的正则!!!没关系,我们的神器BeautifulSoup要上场了!&/p&&p&我们的步骤是:①将获取的源码转换为BeautifulSoup对象②搜索需要的数据&/p&&div class=&highlight&&&pre&&code class=&language-text&&#coding=utf-8
import requests
from bs4 import BeautifulSoup
url = 'http://www.mzitu.com'
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0. UBrowser/6.1. Safari/537.36'}
html = requests.get(url,headers = header)
#使用自带的html.parser解析,速度慢但通用
soup = BeautifulSoup(html.text,'html.parser')
#实际上是第一个class = 'postlist'的div里的所有a 标签是我们要找的信息
all_a = soup.find('div',class_='postlist').find_all('a',target='_blank')
for a in all_a:
title = a.get_text() #提取文本
print(title)
&/code&&/pre&&/div&&p&这样就找到了当页所有套图的标题&/p&&div class=&highlight&&&pre&&code class=&language-text&&注意:BeautifulSoup()返回的类型是&class 'bs4.BeautifulSoup'&
find()返回的类型是&class 'bs4.element.Tag'&
find_all()返回的类型是&class 'bs4.element.ResultSet'&
&class 'bs4.element.ResultSet'&不能再进项find/find_all操作1
&/code&&/pre&&/div&&p&&b&3.进入下载&/b&&/p&&p&点进一个套图之后,发现他是每个页面显示一个图片。 &/p&&figure&&img src=&https://pic4.zhimg.com/v2-b79b52feeae5f2933800bb_b.png& data-caption=&& data-size=&normal& data-rawwidth=&461& data-rawheight=&71& class=&origin_image zh-lightbox-thumb& width=&461& data-original=&https://pic4.zhimg.com/v2-b79b52feeae5f2933800bb_r.png&&&/figure&&p&比如&a href=&//link.zhihu.com/?target=http%3A//www.mzitu.com/26685& class=& external& target=&_blank& rel=&nofollow noreferrer&&&span class=&invisible&&http://www.&/span&&span class=&visible&&mzitu.com/26685&/span&&span class=&invisible&&&/span&&i class=&icon-external&&&/i&&/a&是某个套图的第一页,后面的页数都是再后面跟/和数字&a href=&//link.zhihu.com/?target=http%3A//www.mzitu.com/26685/2& class=& external& target=&_blank& rel=&nofollow noreferrer&&&span class=&invisible&&http://www.&/span&&span class=&visible&&mzitu.com/26685/2&/span&&span class=&invisible&&&/span&&i class=&icon-external&&&/i&&/a& (第二页),那么很简单了,我们只需要找到他一共多少页,然后用循环组成页数就OK了。&/p&&div class=&highlight&&&pre&&code class=&language-text&&#coding=utf-8
import requests
from bs4 import BeautifulSoup
url = 'http://www.mzitu.com/26685'
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0. UBrowser/6.1. Safari/537.36'}
html = requests.get(url,headers = header)
soup = BeautifulSoup(html.text,'html.parser')
#最大页数在span标签中的第10个
pic_max = soup.find_all('span')[10].text
print(pic_max)
#输出每个图片页面的地址
for i in range(1,int(pic_max) + 1):
href = url+'/'+str(i)
print(href)1
&/code&&/pre&&/div&&p&好了,那么我们接下来就是进行寻找图片地址并且保存了,右键妹纸图片,“检查”可以发现&/p&&p&&br&&/p&&figure&&img src=&https://pic3.zhimg.com/v2-a9077edddb5_b.png& data-caption=&& data-size=&normal& data-rawwidth=&1186& data-rawheight=&820& class=&origin_image zh-lightbox-thumb& width=&1186& data-original=&https://pic3.zhimg.com/v2-a9077edddb5_r.png&&&/figure&&p&&br&&/p&&div class=&highlight&&&pre&&code class=&language-text&&&img src=&http://i.meizitu.net/40711w11.jpg& alt=&Beautyleg 美腿写真 No.997 Dora&&11
&/code&&/pre&&/div&&p&那么这就是图片的具体地址了&/p&&p&那么我们的目的就要达成,保存它。&/p&&div class=&highlight&&&pre&&code class=&language-text&&#coding=utf-8
import requests
from bs4 import BeautifulSoup
url = 'http://www.mzitu.com/26685'
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0. UBrowser/6.1. Safari/537.36'}
html = requests.get(url,headers = header)
soup = BeautifulSoup(html.text,'html.parser')
#最大页数在span标签中的第10个
pic_max = soup.find_all('span')[10].text
title = soup.find('h2',class_='main-title').text
#输出每个图片页面的地址
for i in range(1,int(pic_max) + 1):
href = url+'/'+str(i)
html = requests.get(href,headers = header)
mess = BeautifulSoup(html.text,&html.parser&)
#图片地址在img标签alt属性和标题一样的地方
pic_url = mess.find('img',alt = title)
html = requests.get(pic_url['src'],headers = header)
#获取图片的名字方便命名
file_name = pic_url['src'].split(r'/')[-1]
#图片不是文本文件,以二进制格式写入,所以是html.content
f = open(file_name,'wb')
f.write(html.content)
&/code&&/pre&&/div&&p&不出意外你脚本所在的地方会有12张图片&/p&&p&4.批量下载&/p&&p&上面讲了如何下载一个套图,其实所有的套图下载只是加上两重循环。成品如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&#coding=utf-8
import requests
from bs4 import BeautifulSoup
import sys
#安卓端需要此语句
reload(sys)
sys.setdefaultencoding('utf-8')
if(os.name == 'nt'):
print(u'你正在使用win平台')
print(u'你正在使用linux平台')
header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0. UBrowser/6.1. Safari/537.36'}
#http请求头
all_url = 'http://www.mzitu.com'
start_html = requests.get(all_url,headers = header)
path = 'D:/mzitu/'
#找寻最大页数
soup = BeautifulSoup(start_html.text,&html.parser&)
page = soup.find_all('a',class_='page-numbers')
max_page = page[-2].text
same_url = 'http://www.mzitu.com/page/'
for n in range(1,int(max_page)+1):
ul = same_url+str(n)
start_html = requests.get(ul, headers=header)
soup = BeautifulSoup(start_html.text,&html.parser&)
all_a = soup.find('div',class_='postlist').find_all('a',target='_blank')
for a in all_a:
title = a.get_text() #提取文本
if(title != ''):
print(&准备扒取:&+title)
#win不能创建带?的目录
if(os.path.exists(path+title.strip().replace('?',''))):
#print('目录已存在')
os.makedirs(path+title.strip().replace('?',''))
os.chdir(path + title.strip().replace('?',''))
href = a['href']
html = requests.get(href,headers = header)
mess = BeautifulSoup(html.text,&html.parser&)
pic_max = mess.find_all('span')
pic_max = pic_max[10].text #最大页数
if(flag == 1 and len(os.listdir(path+title.strip().replace('?',''))) &= int(pic_max)):
print('已经保存完毕,跳过')
for num in range(1,int(pic_max)+1):
pic = href+'/'+str(num)
html = requests.get(pic,headers = header)
mess = BeautifulSoup(html.text,&html.parser&)
pic_url = mess.find('img',alt = title)
html = requests.get(pic_url['src'],headers = header)
file_name = pic_url['src'].split(r'/')[-1]
f = open(file_name,'wb')
f.write(html.content)
print('完成')
print('第',n,'页完成')
&/code&&/pre&&/div&&p&5.升级多进程版&/p&&div class=&highlight&&&pre&&code class=&language-text&&#coding=utf-8
import requests
from bs4 import BeautifulSoup
from multiprocessing import Pool
import sys
def find_MaxPage():
all_url = 'http://www.mzitu.com'
start_html = requests.get(all_url,headers = header)
#找寻最大页数
soup = BeautifulSoup(start_html.text,&html.parser&)
page = soup.find_all('a',class_='page-numbers')
max_page = page[-2].text
return max_page
def Download(href,header,title,path):
html = requests.get(href,headers = header)
soup = BeautifulSoup(html.text,'html.parser')
pic_max = soup.find_all('span')
pic_max = pic_max[10].text
# 最大页数
if(os.path.exists(path+title.strip().replace('?','')) and len(os.listdir(path+title.strip().replace('?',''))) &= int(pic_max)):
print('已完毕,跳过'+title)
print(&开始扒取:& + title)
os.makedirs(path+title.strip().replace('?',''))
os.chdir(path + title.strip().replace('?',''))
for num in range(1,int(pic_max)+1):
pic = href+'/'+str(num)
#print(pic)
html = requests.get(pic,headers = header)
mess = BeautifulSoup(html.text,&html.parser&)
pic_url = mess.find('img',alt = title)
html = requests.get(pic_url['src'],headers = header)
file_name = pic_url['src'].split(r'/')[-1]
f = open(file_name,'wb')
f.write(html.content)
print('完成'+title)
def download(href,header,title):
html = requests.get(href,headers = header)
soup = BeautifulSoup(html.text,'html.parser')
pic_max = soup.find_all('span')
#for j in pic_max:
#print(j.text)
#print(len(pic_max))
pic_max = pic_max[10].text
# 最大页数
print(pic_max)
#安卓端需要此语句
reload(sys)
sys.setdefaultencoding('utf-8')
if __name__=='__main__':
if (os.name == 'nt'):
print(u'你正在使用win平台')
print(u'你正在使用linux平台')
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0. UBrowser/6.1. Safari/537.36'}
# http请求头
path = 'D:/mzitu/'
max_page = find_MaxPage()
same_url = 'http://www.mzitu.com/page/'
#线程池中线程数
pool = Pool(5)
for n in range(1,int(max_page)+1):
each_url = same_url+str(n)
start_html = requests.get(each_url, headers=header)
soup = BeautifulSoup(start_html.text, &html.parser&)
all_a = soup.find('div', class_='postlist').find_all('a', target='_blank')
for a in all_a:
title = a.get_text()
# 提取文本
if (title != ''):
href = a['href']
pool.apply_async(Download,args=(href,header,title,path))
pool.close()
pool.join()
print('所有图片已下完')
&/code&&/pre&&/div&&hr&&p&你想更深入了解学习Python知识体系,你可以看一下我们花费了一个多月整理了上百小时的几百个知识点体系内容: &/p&&p&&a href=&//link.zhihu.com/?target=http%3A//www.magedu.com/73198.html%3FPython_wenda_zhihu_jinke_ruherumenpythonpachong_question/& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&【超全整理】《Python自动化全能开发从入门到精通》笔记全放送&i class=&icon-external&&&/i&&/a&&/p&
按照我的入门路径整理了一下,同时进行了一些优化,给大家做个分享。先做个简单说明,自己写个简单爬虫是一件非常非常容易的事情,有足够的耐心连一周时间都不用就可以入门。照这篇文章练习,不出一个月你就可以非常熟练的使用各种爬虫。一点都不会错。基础…
&p&想起14年看过的一篇文章。内含非常非常多非常非常丰富的小技巧,我觉得那种技巧可以用高山仰止来形容,从此它就成为了我的收藏夹雷打不动的一篇文章。&/p&&p&如果你已经是个python大牛,那么基本上你应该知道这里面的大多数用法了,但我想你应该也能发现一些你不知道的新技巧。而如果你之前是一个c,c++,java的程序员,同时在学习python,或者干脆就是一个刚刚学习编程的新手,那么你应该会看到很多特别有用能让你感到惊奇的实用技巧,就像我当初一样。&/p&&p&每一个技巧和语言用法都会在一个个实例中展示给大家,也不需要有其他的说明。我已经尽力把每个例子弄的通俗易懂,但是因为读者对python的熟悉程度不同,仍然可能难免有一些晦涩的地方。所以如果这些例子本身无法让你读懂,至少这个例子的标题在你后面去google搜索的时候会帮到你。&/p&&p&整个集合大概是按照难易程度排序,简单常见的在前面,比较少见的在最后。&/p&&h2&1 拆箱&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& a, b, c = 1, 2, 3
&&& a, b, c
&&& a, b, c = [1, 2, 3]
&&& a, b, c
&&& a, b, c = (2 * i + 1 for i in range(3))
&&& a, b, c
&&& a, (b, c), d = [1, (2, 3), 4]
&/code&&/pre&&/div&&h2&2 拆箱变量交换&/h2&&p&代码如下&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& a, b = 1, 2
&&& a, b = b, a
&/code&&/pre&&/div&&h2&3 扩展拆箱(只兼容python3)&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& a, *b, c = [1, 2, 3, 4, 5]
&/code&&/pre&&/div&&h2&4 负数索引&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
&/code&&/pre&&/div&&h2&5 切割列表&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
&&& a[2:8]
[2, 3, 4, 5, 6, 7]
&/code&&/pre&&/div&&h2&6 负数索引切割列表&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
&&& a[-4:-2]
&/code&&/pre&&/div&&h2&7指定步长切割列表&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
&&& a[::2]
[0, 2, 4, 6, 8, 10]
&&& a[::3]
[0, 3, 6, 9]
&&& a[2:8:2]
&/code&&/pre&&/div&&h2&8 负数步长切割列表&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
&&& a[::-1]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
&&& a[::-2]
[10, 8, 6, 4, 2, 0]
&/code&&/pre&&/div&&h2&9 列表切割赋值&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& a = [1, 2, 3, 4, 5]
&&& a[2:3] = [0, 0]
[1, 2, 0, 0, 4, 5]
&&& a[1:1] = [8, 9]
[1, 8, 9, 2, 0, 0, 4, 5]
&&& a[1:-1] = []
&/code&&/pre&&/div&&h2&10 命名列表切割方式&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& a = [0, 1, 2, 3, 4, 5]
&&& LASTTHREE = slice(-3, None)
&&& LASTTHREE
slice(-3, None, None)
&&& a[LASTTHREE]
&/code&&/pre&&/div&&h2&11 列表以及迭代器的压缩和解压缩&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& a = [1, 2, 3]
&&& b = ['a', 'b', 'c']
&&& z = zip(a, b)
[(1, 'a'), (2, 'b'), (3, 'c')]
&&& zip(*z)
[(1, 2, 3), ('a', 'b', 'c')]
&/code&&/pre&&/div&&h2&12 列表相邻元素压缩器&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& a = [1, 2, 3, 4, 5, 6]
&&& zip(*([iter(a)] * 2))
[(1, 2), (3, 4), (5, 6)]
&&& group_adjacent = lambda a, k: zip(*([iter(a)] * k))
&&& group_adjacent(a, 3)
[(1, 2, 3), (4, 5, 6)]
&&& group_adjacent(a, 2)
[(1, 2), (3, 4), (5, 6)]
&&& group_adjacent(a, 1)
[(1,), (2,), (3,), (4,), (5,), (6,)]
&&& zip(a[::2], a[1::2])
[(1, 2), (3, 4), (5, 6)]
&&& zip(a[::3], a[1::3], a[2::3])
[(1, 2, 3), (4, 5, 6)]
&&& group_adjacent = lambda a, k: zip(*(a[i::k] for i in range(k)))
&&& group_adjacent(a, 3)
[(1, 2, 3), (4, 5, 6)]
&&& group_adjacent(a, 2)
[(1, 2), (3, 4), (5, 6)]
&&& group_adjacent(a, 1)
[(1,), (2,), (3,), (4,), (5,), (6,)]
&/code&&/pre&&/div&&h2&13 在列表中用压缩器和迭代器滑动取值窗口&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& def n_grams(a, n):
z = [iter(a[i:]) for i in range(n)]
return zip(*z)
&&& a = [1, 2, 3, 4, 5, 6]
&&& n_grams(a, 3)
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]
&&& n_grams(a, 2)
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
&&& n_grams(a, 4)
[(1, 2, 3, 4), (2, 3, 4, 5), (3, 4, 5, 6)]
&/code&&/pre&&/div&&h2&14 用压缩器反转字典&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
&&& m.items()
[('a', 1), ('c', 3), ('b', 2), ('d', 4)]
&&& zip(m.values(), m.keys())
[(1, 'a'), (3, 'c'), (2, 'b'), (4, 'd')]
&&& mi = dict(zip(m.values(), m.keys()))
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
&/code&&/pre&&/div&&h2&15 列表展开&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& a = [[1, 2], [3, 4], [5, 6]]
&&& list(itertools.chain.from_iterable(a))
[1, 2, 3, 4, 5, 6]
&&& sum(a, [])
[1, 2, 3, 4, 5, 6]
&&& [x for l in a for x in l]
[1, 2, 3, 4, 5, 6]
&&& a = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
&&& [x for l1 in a for l2 in l1 for x in l2]
[1, 2, 3, 4, 5, 6, 7, 8]
&&& a = [1, 2, [3, 4], [[5, 6], [7, 8]]]
&&& flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]
&&& flatten(a)
&/code&&/pre&&/div&&p&[1, 2, 3, 4, 5, 6, 7, 8]&/p&&h2&16 生成器表达式&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& g = (x ** 2 for x in xrange(10))
&&& next(g)
&&& next(g)
&&& next(g)
&&& next(g)
&&& sum(x ** 3 for x in xrange(10))
&&& sum(x ** 3 for x in xrange(10) if x % 3 == 1)
&/code&&/pre&&/div&&h2&17 字典推导&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& m = {x: x ** 2 for x in range(5)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
&&& m = {x: 'A' + str(x) for x in range(10)}
{0: 'A0', 1: 'A1', 2: 'A2', 3: 'A3', 4: 'A4', 5: 'A5', 6: 'A6', 7: 'A7', 8: 'A8', 9: 'A9'}
&/code&&/pre&&/div&&h2&18 用字典推导反转字典&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
{'d': 4, 'a': 1, 'b': 2, 'c': 3}
&&& {v: k for k, v in m.items()}
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
&/code&&/pre&&/div&&h2&19 命名元组&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& Point = collections.namedtuple('Point', ['x', 'y'])
&&& p = Point(x=1.0, y=2.0)
Point(x=1.0, y=2.0)
&/code&&/pre&&/div&&h2&20 继承命名元组&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& class Point(collections.namedtuple('PointBase', ['x', 'y'])):
__slots__ = ()
def __add__(self, other):
return Point(x=self.x + other.x, y=self.y + other.y)
&&& p = Point(x=1.0, y=2.0)
&&& q = Point(x=2.0, y=3.0)
Point(x=3.0, y=5.0)
&/code&&/pre&&/div&&h2&21 操作集合&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& A = {1, 2, 3, 3}
set([1, 2, 3])
&&& B = {3, 4, 5, 6, 7}
set([3, 4, 5, 6, 7])
set([1, 2, 3, 4, 5, 6, 7])
set([1, 2])
set([4, 5, 6, 7])
set([1, 2, 4, 5, 6, 7])
&&& (A ^ B) == ((A - B) | (B - A))
&/code&&/pre&&/div&&h2&22 操作多重集合&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& A = collections.Counter([1, 2, 2])
&&& B = collections.Counter([2, 2, 3])
Counter({2: 2, 1: 1})
Counter({2: 2, 3: 1})
Counter({2: 2, 1: 1, 3: 1})
Counter({2: 2})
Counter({2: 4, 1: 1, 3: 1})
Counter({1: 1})
Counter({3: 1})
&/code&&/pre&&/div&&h2&23 统计在可迭代器中最常出现的元素&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& A = collections.Counter([1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 6, 7])
Counter({3: 4, 1: 2, 2: 2, 4: 1, 5: 1, 6: 1, 7: 1})
&&& A.most_common(1)
&&& A.most_common(3)
[(3, 4), (1, 2), (2, 2)]
&/code&&/pre&&/div&&h2&24 两端都可操作的队列&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& Q = collections.deque()
&&& Q.append(1)
&&& Q.appendleft(2)
&&& Q.extend([3, 4])
&&& Q.extendleft([5, 6])
deque([6, 5, 2, 1, 3, 4])
&&& Q.pop()
&&& Q.popleft()
deque([5, 2, 1, 3])
&&& Q.rotate(3)
deque([2, 1, 3, 5])
&&& Q.rotate(-3)
deque([5, 2, 1, 3])
&/code&&/pre&&/div&&h2&25 有最大长度的双端队列&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& last_three = collections.deque(maxlen=3)
&&& for i in xrange(10):
last_three.append(i)
print ', '.join(str(x) for x in last_three)
&/code&&/pre&&/div&&h2&26 可排序词典&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& m = dict((str(x), x) for x in range(10))
&&& print ', '.join(m.keys())
1, 0, 3, 2, 5, 4, 7, 6, 9, 8
&&& m = collections.OrderedDict((str(x), x) for x in range(10))
&&& print ', '.join(m.keys())
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
&&& m = collections.OrderedDict((str(x), x) for x in range(10, 0, -1))
&&& print ', '.join(m.keys())
10, 9, 8, 7, 6, 5, 4, 3, 2, 1
&/code&&/pre&&/div&&h2&27 默认词典&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& m = dict()
&&& m['a']
Traceback (most recent call last):
File &&stdin&&, line 1, in &module&
KeyError: 'a'
&&& m = collections.defaultdict(int)
&&& m['a']
&&& m['b']
&&& m = collections.defaultdict(str)
&&& m['a']
&&& m['b'] += 'a'
&&& m['b']
&&& m = collections.defaultdict(lambda: '[default value]')
&&& m['a']
'[default value]'
&&& m['b']
'[default value]'
&/code&&/pre&&/div&&h2&28 默认字典的简单树状表达&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& import json
&&& tree = lambda: collections.defaultdict(tree)
&&& root = tree()
&&& root['menu']['id'] = 'file'
&&& root['menu']['value'] = 'File'
&&& root['menu']['menuitems']['new']['value'] = 'New'
&&& root['menu']['menuitems']['new']['onclick'] = 'new();'
&&& root['menu']['menuitems']['open']['value'] = 'Open'
&&& root['menu']['menuitems']['open']['onclick'] = 'open();'
&&& root['menu']['menuitems']['close']['value'] = 'Close'
&&& root['menu']['menuitems']['close']['onclick'] = 'close();'
&&& print json.dumps(root, sort_keys=True, indent=4, separators=(',', ': '))
&id&: &file&,
&menuitems&: {
&close&: {
&onclick&: &close();&,
&value&: &Close&
&onclick&: &new();&,
&value&: &New&
&onclick&: &open();&,
&value&: &Open&
&value&: &File&
&/code&&/pre&&/div&&h2&29 对象到唯一计数的映射&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& import itertools, collections
&&& value_to_numeric_map = collections.defaultdict(itertools.count().next)
&&& value_to_numeric_map['a']
&&& value_to_numeric_map['b']
&&& value_to_numeric_map['c']
&&& value_to_numeric_map['a']
&&& value_to_numeric_map['b']
&/code&&/pre&&/div&&h2&30 最大和最小的几个列表元素&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& a = [random.randint(0, 100) for __ in xrange(100)]
&&& heapq.nsmallest(5, a)
[3, 3, 5, 6, 8]
&&& heapq.nlargest(5, a)
[100, 100, 99, 98, 98]
&/code&&/pre&&/div&&h2&31 两个列表的笛卡尔积&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& for p in itertools.product([1, 2, 3], [4, 5]):
&&& for p in itertools.product([0, 1], repeat=4):
print ''.join(str(x) for x in p)
&/code&&/pre&&/div&&h2&32 列表组合和列表元素替代组合&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& for c in itertools.combinations([1, 2, 3, 4, 5], 3):
print ''.join(str(x) for x in c)
&&& for c in itertools.combinations_with_replacement([1, 2, 3], 2):
print ''.join(str(x) for x in c)
&/code&&/pre&&/div&&h2&33 列表元素排列组合&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& for p in itertools.permutations([1, 2, 3, 4]):
print ''.join(str(x) for x in p)
&/code&&/pre&&/div&&h2&34 可链接迭代器&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& a = [1, 2, 3, 4]
&&& for p in itertools.chain(itertools.combinations(a, 2), itertools.combinations(a, 3)):
&&& for subset in itertools.chain.from_iterable(itertools.combinations(a, n) for n in range(len(a) + 1))
print subset
(1, 2, 3, 4)
&/code&&/pre&&/div&&h2&35 根据文件指定列类聚&/h2&&p&代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&&& import itertools
&&& with open('contactlenses.csv', 'r') as infile:
data = [line.strip().split(',') for line in infile]
&&& data = data[1:]
&&& def print_data(rows):
print 'n'.join('t'.join('{: &16}'.format(s) for s in row) for row in rows)
&&& print_data(data)
hypermetrope
hypermetrope
hypermetrope
hypermetrope
pre-presbyopic
pre-presbyopic
pre-presbyopic
pre-presbyopic
pre-presbyopic
hypermetrope
pre-presbyopic
hypermetrope
pre-presbyopic
hypermetrope
pre-presbyopic
hypermetrope
presbyopic
presbyopic
presbyopic
presbyopic
presbyopic
hypermetrope
presbyopic
hypermetrope
presbyopic
hypermetrope
presbyopic
hypermetrope
&&& data.sort(key=lambda r: r[-1])
&&& for value, group in itertools.groupby(data, lambda r: r[-1]):
print '-----------'
print 'Group: ' + value
print_data(group)
-----------
Group: hard
hypermetrope
pre-presbyopic
presbyopic
-----------
Group: none
hypermetrope
hypermetrope
pre-presbyopic
pre-presbyopic
pre-presbyopic
hypermetrope
pre-presbyopic
hypermetrope
pre-presbyopic
hypermetrope
presbyopic
presbyopic
presbyopic
presbyopic
hypermetrope
presbyopic
hypermetrope
presbyopic
hypermetrope
-----------
Group: soft
hypermetrope
pre-presbyopic
pre-presbyopic
hypermetrope
presbyopic
hypermetrope
&/code&&/pre&&/div&&p&原文链接在这里:&a href=&//link.zhihu.com/?target=http%3A//www.phperz.com/article/14/.html& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Python编程小技巧35则&i class=&icon-external&&&/i&&/a&&/p&&hr&&p&你想更深入了解学习Python知识体系,你可以看一下我们花费了一个多月整理了上百小时的几百个知识点体系内容: &/p&&p&&a href=&//link.zhihu.com/?target=http%3A//www.magedu.com/73198.html%3FPython_wenda_zhihu_jinke_pythonyounaxieyouyadedaimashixianrangzijidedaimagengpythonic_question/& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&【超全整理】《Python自动化全能开发从入门到精通》笔记全放送&i class=&icon-external&&&/i&&/a&&/p&
想起14年看过的一篇文章。内含非常非常多非常非常丰富的小技巧,我觉得那种技巧可以用高山仰止来形容,从此它就成为了我的收藏夹雷打不动的一篇文章。如果你已经是个python大牛,那么基本上你应该知道这里面的大多数用法了,但我想你应该也能发现一些你不知…
更新:建议下载文件,链接:&a href=&//link.zhihu.com/?target=http%3A//pan.baidu.com/s/1dERLTPR& class=& external& target=&_blank& rel=&nofollow noreferrer&&&span class=&invisible&&http://&/span&&span class=&visible&&pan.baidu.com/s/1dERLTP&/span&&span class=&invisible&&R&/span&&span class=&ellipsis&&&/span&&i class=&icon-external&&&/i&&/a& 密码:0h3q&br&————————————————————————————————————————&br&看到这个话题,我决定送给职场新人一个福利~~&br&&br&&br&我刚毕业那会,Excel数据透视表都不会,后来进入DBA部门用得更少了。&br&工作过程中一个做excel的妹子找我抱怨,做一个表要花一两个小时,甚至三四个小时,请教我能否想想办法,我用R写个程序可以。考虑到妹子家里公司都要做事,不太想安装R。我想到了VBA,在大学时学过一点VB,正好练练手。&br&花一天整理妹子的需求,用一周学习,然后就写出了&br&3个自定义函数&br&2个自动更新数据&br&后来写着写着就顺手,经常帮妹子写报表自动化程序。&br&导致妹子对我产生依赖性,她每天就想按几个键然后工作都完成了。&br&我建议她可以看看我的代码,我都写好注释了,你可以按照注释去改参数,就不用天天问我了,但妹子看不懂,我教了几遍遂放弃。&br&&br&对了上面说的福利,当然是贴代码,这份福利给文职类的处理excel的新人,程序员不要捣乱。&br&&b&情景1&/b&:一个工作簿,你按照地区或者部门等你自己的需要拆成不同的工作簿(需求是不是很简单,nonono,单独做一个当然简单,但是我贴出来肯定是这个代码是通用的。比如你想拆第几行开始娜一列都可以,会有选项让你一步一步选择)&br&&b&情景2:&/b&比如拆完,有30张表,你想发给30个不同的人看?你是不是要同时写30封邮呢&br&关于情景1,的工作时间:如果一张总表有三十城市,要按照城市拆成三十个工作簿,不断复制+改工作簿名,个人觉得至少得二十分钟吧,还有容易出错的概率。&br&关于情景2的工作时间:这个就更麻烦了。三十个城市名,要下发给三十个不同分公司的人,而且不同分公司的人,不是只有一个人。你第一次发,如果邮箱有群组还好,但是你始终得写三十封邮件,还要注意选择工作簿不能出错,邮件主题内容不能出错。预估这个工作时间至少得一个小时,平均一封邮件2分钟。&br&&br&情景1+情景2时间=一小时二十分钟(据我观察,历史五个人做这件事出错率100%,不是城市名写错了,就发错工作簿了)&br&&br&不知道大家看懂了没= =&br&好了开始写步骤贴代码,我会尽量用最通俗的语言讲清逻辑关系&br&步骤1:建立两个sheet,点击sheet ,右击查看代码(先检查excel是否启用宏,要启用宏哦)&br&&figure&&img src=&https://pic2.zhimg.com/71ce4eb04bc_b.png& data-rawwidth=&174& data-rawheight=&37& class=&content_image& width=&174&&&/figure&&br&&figure&&img src=&https://pic2.zhimg.com/98bfde513c_b.png& data-rawwidth=&231& data-rawheight=&258& class=&content_image& width=&231&&&/figure&&br&&br&&figure&&img src=&https://pic4.zhimg.com/e77a6697abde2ecf39d3bb_b.png& data-rawwidth=&502& data-rawheight=&251& class=&origin_image zh-lightbox-thumb& width=&502& data-original=&https://pic4.zhimg.com/e77a6697abde2ecf39d3bb_r.png&&&/figure&&br&插入窗体和模块,按模块,把以下这串代码复制进去&br&&figure&&img src=&https://pic3.zhimg.com/f011a647c1eb257ee09b43bae14d97c6_b.png& data-rawwidth=&612& data-rawheight=&438& class=&origin_image zh-lightbox-thumb& width=&612& data-original=&https://pic3.zhimg.com/f011a647c1eb257ee09b43bae14d97c6_r.png&&&/figure&再按窗体,设置成这样&figure&&img src=&https://pic4.zhimg.com/ff74ea61d86d46b808440b_b.png& data-rawwidth=&534& data-rawheight=&279& class=&origin_image zh-lightbox-thumb& width=&534& data-original=&https://pic4.zhimg.com/ff74ea61d86d46b808440b_r.png&&&/figure&&br&然后看到代码,拉到最后,能看到一个是邮件签名,一个是邮箱配置,你自己填上即可,邮件内容可以自己改&br&&figure&&img src=&https://pic4.zhimg.com/2e24e797c08328cee1a7_b.png& data-rawwidth=&657& data-rawheight=&542& class=&origin_image zh-lightbox-thumb& width=&657& data-original=&https://pic4.zhimg.com/2e24e797c08328cee1a7_r.png&&&/figure&&br&截止到这步,代表所有准备工作都完成了,咱们开始测试吧^_^&br&29个城市,我拆成29个工作簿,点击宏&br&&figure&&img src=&https://pic4.zhimg.com/4ccdbcd8b10effbd86dc7_b.png& data-rawwidth=&975& data-rawheight=&476& class=&origin_image zh-lightbox-thumb& width=&975& data-original=&https://pic4.zhimg.com/4ccdbcd8b10effbd86dc7_r.png&&&/figure&&br&&figure&&img src=&https://pic4.zhimg.com/3af254d33aa55b3edb16fa3_b.png& data-rawwidth=&389& data-rawheight=&415& class=&content_image& width=&389&&&/figure&&br&&figure&&img src=&https://pic3.zhimg.com/c26bd752b89a5b7df8bb2_b.png& data-rawwidth=&244& data-rawheight=&228& class=&content_image& width=&244&&&/figure&&figure&&img src=&https://pic4.zhimg.com/e2cfa90d3c3b52cafa3d61f_b.png& data-rawwidth=&500& data-rawheight=&273& class=&origin_image zh-lightbox-thumb& width=&500& data-original=&https://pic4.zhimg.com/e2cfa90d3c3b52cafa3d61f_r.png&&&/figure&&br&&br&&figure&&img src=&https://pic1.zhimg.com/9fc7c3eeacc381f1840c_b.png& data-rawwidth=&405& data-rawheight=&160& class=&content_image& width=&405&&&/figure&&br&按完确定大概10秒后,跟你excel同个文件夹内,会生成拆分的文件夹,你点进去&br&&br&&figure&&img src=&https://pic1.zhimg.com/573c9c14bd0ee11fe83c80_b.png& data-rawwidth=&615& data-rawheight=&106& class=&origin_image zh-lightbox-thumb& width=&615& data-original=&https://pic1.zhimg.com/573c9c14bd0ee11fe83c80_r.png&&&/figure&已经生成了,如果没有想要发邮件的同学,在这里就可以结束啦。&br&&figure&&img src=&https://pic2.zhimg.com/928e8b78cc1a3cb5edad_b.png& data-rawwidth=&602& data-rawheight=&589& class=&origin_image zh-lightbox-thumb& width=&602& data-original=&https://pic2.zhimg.com/928e8b78cc1a3cb5edad_r.png&&&/figure&打开工作簿看看,拆分如何&br&&figure&&img src=&https://pic2.zhimg.com/1f33add9aee1b63a1e630a7f5b97d425_b.png& data-rawwidth=&651& data-rawheight=&184& class=&origin_image zh-lightbox-thumb& width=&651& data-original=&https://pic2.zhimg.com/1f33add9aee1b63a1e630a7f5b97d425_r.png&&&/figure&&br&想把三十个工作簿发送邮件的同学,注意看下面,转到通讯录的那个sheet,&br&&br&&figure&&img src=&https://pic2.zhimg.com/66e2ac27ff_b.png& data-rawwidth=&986& data-rawheight=&393& class=&origin_image zh-lightbox-thumb& width=&986& data-original=&https://pic2.zhimg.com/66e2ac27ff_r.png&&&/figure&&br&&figure&&img src=&https://pic1.zhimg.com/aee1d2f4be44ddc32cd048ec78bc2890_b.png& data-rawwidth=&385& data-rawheight=&409& class=&content_image& width=&385&&&/figure&&figure&&img src=&https://pic3.zhimg.com/8fe83022adc58a00cdb02c12_b.png& data-rawwidth=&503& data-rawheight=&340& class=&origin_image zh-lightbox-thumb& width=&503& data-original=&https://pic3.zhimg.com/8fe83022adc58a00cdb02c12_r.png&&&/figure&这里点击一次文件夹,直接按确定,不用双击进入文件夹&figure&&img src=&https://pic2.zhimg.com/bca6ffedd_b.png& data-rawwidth=&800& data-rawheight=&414& class=&origin_image zh-lightbox-thumb& width=&800& data-original=&https://pic2.zhimg.com/bca6ffedd_r.png&&&/figure&&br&&figure&&img src=&https://pic1.zhimg.com/adf67b064b32aeab79810_b.png& data-rawwidth=&398& data-rawheight=&193& class=&content_image& width=&398&&&/figure&&br&按完确定后,这时候按照工作簿数来算时间,基本上每秒一个城市,也就是一个工作簿。等到这个提示出来之后,你就可以直接看到结果了。&br&&figure&&img src=&https://pic1.zhimg.com/ff44fb2b39b1dfacaf954_b.png& data-rawwidth=&1133& data-rawheight=&674& class=&origin_image zh-lightbox-thumb& width=&1133& data-original=&https://pic1.zhimg.com/ff44fb2b39b1dfacaf954_r.png&&&/figure&&br&然后你在看,是否有收到邮件&br&打开你的邮箱&figure&&img src=&https://pic1.zhimg.com/37f39ed37d6a4dddfa1b0_b.png& data-rawwidth=&920& data-rawheight=&29& class=&origin_image zh-lightbox-thumb& width=&920& data-original=&https://pic1.zhimg.com/37f39ed37d6a4dddfa1b0_r.png&&&/figure&&br&收到啦&br&&figure&&img src=&https://pic2.zhimg.com/40f4fb4a2dca641d193b64b_b.png& data-rawwidth=&480& data-rawheight=&585& class=&origin_image zh-lightbox-thumb& width=&480& data-original=&https://pic2.zhimg.com/40f4fb4a2dca641d193b64b_r.png&&&/figure&&br&整套点击+运行大约三分钟&br&代码:&br&Sub 通用拆分()&br&'On Error Resume Next&br&Application.ScreenUpdating = False '关闭屏幕更新&br&Application.DisplayAlerts = False '关闭提示事件,防止删除表格时提示&br&&br&Dim Pro, Wb1, Wb2, St1, Sht, Rng, Itm, StRow, Pth&br&&br&Set Wb1 = ThisWorkbook&br&Set St1 = ActiveSheet&br&&br&a = MsgBox(&当前文件为:& & Wb1.Name & Chr(10) & &当前表格为:& & St1.Name & Chr(10) & Chr(10) & &点击 确定 继续运行,& & Chr(10) & &点击 取消 退出程序。&, 1)&br&If a = 2 Then '如果点了取消,就退出程序&br&
Exit Sub&br&End If&br&&br&b = InputBox(&请输入拆分列表头所在的单元格位置。& & Chr(10) & &例如:要拆分的列位于C列,表头是第3行,就输入“C3”&)&br&If b = && Then&br&
MsgBox (&未输入拆分表头,程序退出&)&br&
Exit Sub&br&End If&br&&br&rowx = St1.Range(b).Row&br&colx = St1.Range(b).Column&br&&br&Set Pro = CreateObject(&Scripting.Dictionary&) '建立一个以省份为关键字的字典&br&StRow = St1.Cells.Find(&*&, SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).EntireRow.Row '确定当前文件行数&br&&br&St1.Range(rowx & &:& & rowx).AutoFilter Field:=colx, Criteria1:=&*&
'取消筛选&br&For Each Rng In St1.Range(St1.Cells(rowx + 1, colx), St1.Cells(StRow, colx)) '&br&
If Not Pro.exists(Rng.Value) And Not IsError(Rng.Value) Then Pro.Add Rng.Value, Rng.Value '判断当前表格的值是否在字典内,如果不在,就添加到字典内&br&Next&br&&br&namex = InputBox(&请输入文件名的自定义字段,& & Chr(10) & &例如输入“收款明细”,就会生成“上海-收款明细.xlsx”文件&, &&, St1.Name)&br&&br&For Each Itm In Pro.Items '针对字典内的每个值进行一次操作(每个省份循环一次)&br&
St1.Copy&br&
Set Wb2 = ActiveWorkbook&br&
Set Sht = ActiveSheet&br&
Sht.Range(rowx & &:& & rowx).AutoFilter Field:=colx, Criteria1:=&&&& & Itm, Operator:=xlAnd
'筛选列,筛选值为不符合当前省份&br&
Sht.Range(Sht.Cells(rowx + 1, colx), Sht.Cells(StRow, colx)).SpecialCells(xlCellTypeVisible).Delete Shift:=xlUp '删除被筛选出来的行(删掉不为当前省份的行)&br&
Sht.Range(rowx & &:& & rowx).AutoFilter '取消筛选&br&
ActiveWindow.SmallScroll Down:=-StRow&br&
ActiveWindow.SmallScroll ToRight:=-100&br&&br&
If Dir(Wb1.Path & &\拆分\&, vbDirectory) = && Then MkDir ThisWorkbook.Path & &\拆分\& '看看当前文件夹内是否存在&拆分&文件夹,如果没有就创建一个&br&
Pth = Wb1.Path & &\拆分\& & Itm & &-& & namex & &.xls&&br&
Wb2.SaveAs Filename:=Pth, FileFormat:=xlExcel8, Password:=&&, WriteResPassword:=&&, ReadOnlyRecommended:=False, CreateBackup:=False&br&
Wb2.Close '关闭表格&br&&br&Next&br&&br&Set Pro = Nothing '释放变量&br&Set Wb1 = Nothing&br&Set Wb2 = Nothing&br&Set St1 = Nothing&br&Set Sht = Nothing&br&Set Rng = Nothing&br&Set Itm = Nothing&br&Set StRow = Nothing&br&Set Pth = Nothing&br&&br&Application.ScreenUpdating = True '打开屏幕更新&br&Application.DisplayAlerts = True '打开提示事件&br&End Sub&br&Sub 通用发送邮件()&br&'On Error Resume Next&br&Dim cm As Variant&br&&br&UserForm1.Show&br&UserName = UserForm1.ComboBox1&br&UserPass = UserForm1.TextBox1.Value&br&&br&With Application.FileDialog(msoFileDialogFolderPicker)&br&
.InitialFileName = ActiveWorkbook.Path & &\&&br&
If .Show = -1 Then&br&
Pth = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems.Item(1) & &\&&br&
End If&br&End With&br&&br&'定义文件夹&br&Dim FS, F, FF, Fil, BName, EName&br&Set FS = CreateObject(&Scripting.FileSystemObject&)&br&Set F = FS.GetFolder(Pth)&br&Set FF = F.Files&br&&br&If FF Is Nothing Or F Is Nothing Then&br&
MsgBox (&文件或文件夹错误,请查证在本文件目录内存在'拆分'文件夹,并且已经生成拆分文件&)&br&
Exit Sub&br&End If&br&'保存文件信息&br&Dim FN(1 To 10000, 1 To 3)&br&i = 0&br&For Each Fil In FF&br&
i = i + 1&br&
FN(i, 1) = FS.GetBaseName(Fil)&br&
FN(i, 2) = FS.GetExtensionName(Fil)&br&
FN(i, 3) = Left(FN(i, 1), InStr(1, FN(i, 1), &-&) - 1)&br&Next&br&&br&Set Sht = ThisWorkbook.Sheets(&邮件联系人&)&br&colnew = Sht.Cells(1, Columns.Count).End(xlToLeft).Column + 1 '联系人空白列(用于记录发送结果)&br&Sht.Cells(1, colnew).Value = Pth & Chr(10) & Date & & & & Time & & 发送结果&&br&&br&tex = InputBox(&请输入邮件正文自定义段&)&br&&br&For m = 1 To i&br&
Err.Clear&br&
linkman = &&&br&
emailx = &&&br&
Set bbb = Sht.Range(&a:a&).Find(FN(m, 3))&br&
If bbb Is Nothing Then&br&
rownew = Sht.Range(&a60000&).End(xlUp).Row + 1&br&
Sht.Cells(rownew, 1).Value = FN(m, 3)&br&
Sht.Cells(rownew, colnew).Value = &未找到发件人&&br&
mg = mg & FN(m, 3) & Left(&
&, 10 - Len(FN(m, 3)) * 2) & &未找到发件人& & Chr(13)&br&
GoTo line5&br&
End If&br&
For n = 1 To Sht.Range(&a60000&).End(xlUp).Row '循环查找联系人姓名和邮件地址&br&
If FN(m, 3) = Sht.Cells(n, 1).Value Then&br&
linkman = linkman & Sht.Cells(n, 2).Value & &、&&br&
emailx = emailx & Replace(Sht.Cells(n, 7).Value, &;&, &&) & &,&&br&
End If&br&
If Len(emailx) & 2 Then '如果邮件地址是空,那就不发送本城市&br&
bbb.Offset(0, colnew - 1).Value = &无邮件地址&&br&
mg = mg & FN(m, 3) & Left(&
&, 10 - Len(FN(m, 3)) * 2) & &无邮件地址& & Chr(13)&br&
GoTo line5&br&
End If&br&
linkman = Left(linkman, Len(linkman) - 1) '删掉最后一个符号&br&
emailx = Left(emailx, Len(emailx) - 1)&br&&br&&br&
Set cm = CreateObject(&CDO.Message&)
'创建对象&br&
cm.From = UserName
'设置发信人的邮箱&br&
cm.To = emailx
'设置收信人的邮箱&br&
cm.Subject = FN(m, 1)
'设定邮件的主题&br&&br&
cm.TextBody = &亲爱的********:& _&br&
& Chr(10) & &
附件为 & & FN(m, 1) & &,请查收。& & Chr(10) & tex _&br&
& Chr(10) & &谢谢!& _&br&
& Chr(10) & & _______________________________________________________& _&br&
& Chr(10) & & **部门
& Chr(10) & & 姓名
& Chr(10) & & 手机:*********
& Chr(10) & & 电话:*********
& Chr(10) & & Email:*********
& Chr(10) & & 地址:******************
'邮件正文&br&&br&
cm.AddAttachment Pth & FN(m, 1) & &.& & FN(m, 2)
'添加附件&br&
stUl = &&a href=&//link.zhihu.com/?target=http%3A//schemas.microsoft.com/cdo/configuration/& class=& external& target=&_blank& rel=&nofollow noreferrer&&&span class=&invisible&&http://&/span&&span class=&visible&&schemas.microsoft.com/c&/span&&span class=&invisible&&do/configuration/&/span&&span class=&ellipsis&&&/span&&i class=&icon-external&&&/i&&/a&&&br&
With cm.Configuration.Fields&br&
.Item(stUl & &smtpserver&) = &&a href=&//link.zhihu.com/?target=http%3A//mail.qq.com& class=& external& target=&_blank& rel=&nofollow noreferrer&&&span class=&invisible&&http://&/span&&span class=&visible&&mail.qq.com&/span&&span class=&invisible&&&/span&&i class=&icon-external&&&/i&&/a&&
'SMTP服务器地址&br&
.Item(stUl & &smtpserverport&) = 25
'SMTP服务器端口&br&
.Item(stUl & &sendusing&) = 2
'发送端口&br&
.Item(stUl & &smtpauthenticate&) = 1&br&
.Item(stUl & &sendusername&) = UserName
'发送方邮箱名称&br&
.Item(stUl & &sendpassword&) = UserPass
'发送方邮箱密码&&br&
.Update&br&
End With&br&
'发送&br&&br&
'生成反馈信息&br&&br&
If Err.Number = 0 Then&br&
mg = mg & FN(m, 3) & Left(&
&, 10 - Len(FN(m, 3)) * 2) & &发送成功& & Chr(13)&br&
bbb.Offset(0, colnew - 1).Value = &发送成功&&br&
mg = mg & FN(m, 3) & Left(&
&, 10 - Len(FN(m, 3)) * 2) & &发送失败& & Chr(13)&br&
bbb.Offset(0, colnew - 1).Value = &发送失败&&br&
End If&br&
Set cm = Nothing
'发送成功后即时释放对象&br&line5:&br&Next&br&&br&MsgBox (Left(mg, Len(mg) - 1)) '确认结果&br&&br&End Sub&br&&br&——————————————————————————————————&br&谢谢大家的赞,那我就再贴一个给职场小白&br&前面拆分,肯定有合并,再贴一个合并工作簿的代码,也超级简单的哦。&br&&br&开始:&br&新建一个空白工作簿&br&还是一样右击sheet——查看代码,这次不用建立模块,直接把代码贴进去即可&br&&figure&&img src=&https://pic4.zhimg.com/04f6b816beb5cdff79a8db_b.png& data-rawwidth=&829& data-rawheight=&751& class=&origin_image zh-lightbox-thumb& width=&829& data-original=&https://pic4.zhimg.com/04f6b816beb5cdff79a8db_r.png&&&/figure&&br&&figure&&img src=&https://pic3.zhimg.com/b619dea86e_b.png& data-rawwidth=&502& data-rawheight=&514& class=&origin_image zh-lightbox-thumb& width=&502& data-original=&https://pic3.zhimg.com/b619dea86e_r.png&&&/figure&点击执行后,让你选择文件夹,你的先把要合并的所有工作簿放在一个文件夹内&br&&figure&&img src=&https://pic4.zhimg.com/c059ec89c7cc24b2c05b_b.png& data-rawwidth=&381& data-rawheight=&354& class=&content_image& width=&381&&&/figure&数据是这样的&br&&figure&&img src=&https://pic1.zhimg.com/d05a8a953d4394cfceba8_b.png& data-rawwidth=&457& data-rawheight=&197& class=&origin_image zh-lightbox-thumb& width=&457& data-original=&https://pic1.zhimg.com/d05a8a953d4394cfceba8_r.png&&&/figure&&br&&br&&figure&&img src=&https://pic4.zhimg.com/73cfafdc5f27d3f37acba3_b.png& data-rawwidth=&593& data-rawheight=&111& class=&origin_image zh-lightbox-thumb& width=&593& data-original=&https://pic4.zhimg.com/73cfafdc5f27d3f37acba3_r.png&&&/figure&点击文件夹执行后&br&&figure&&img src=&https://pic4.zhimg.com/c9284cea7f6c1f5cad55d62ba38605bb_b.png& data-rawwidth=&201& data-rawheight=&189& class=&content_image& width=&201&&&/figure&按确定后,数据就好了。&br&&figure&&img src=&https://pic4.zhimg.com/d1aa4a516f_b.png& data-rawwidth=&497& data-rawheight=&501& class=&origin_image zh-lightbox-thumb& width=&497& data-original=&https://pic4.zhimg.com/d1aa4a516f_r.png&&&/figure&&br&对了,工作簿名称不一样也不要紧哦&br&比如这样....&br&&figure&&img src=&https://pic3.zhimg.com/bc8bdee3b96a32916b5da_b.png& data-rawwidth=&598& data-rawheight=&84& class=&origin_image zh-lightbox-thumb& width=&598& data-original=&https://pic3.zhimg.com/bc8bdee3b96a32916b5da_r.png&&&/figure&代码:&br&Sub 文件合并()&br&&br&&br&Application.ScreenUpdating = False&br&'On Error Resume Next&br&&br&&br&Dim Pth As String&br&&br&Set wst1 = ActiveSheet&br&row1 = 0&br&wst1.Cells.Delete Shift:=xlUp&br&&br&&br&'打开文件夹&br&Dim shell, s&br&Set shell = CreateObject(&Shell.Application&)&br&Set fl = shell.BrowseForFolder(0, &请选择文件夹&, 0, Pth)&br&If fl Is Nothing Then Exit Sub&br&&br&Pth = fl.self.Path & &\&&br&&br&&br&'定义文件夹&br&Dim FS, F, FF, Fil, BName, EName&br&Set FS = CreateObject(&Scripting.FileSystemObject&)&br&Set F = FS.GetFolder(Pth)&br&Set FF = F.Files&br&&br&&br&For Each Fil In FF&br&
BName = FS.GetBaseName(Fil)&br&
EName = FS.GetExtensionName(Fil)&br&
If EName = &xls& Or EName = &xlsx& Or EName = &XLS& Or EName = &XLSX& Then&br&
Workbooks.Open (Fil)&br&
Set wst2 = ActiveSheet&br&
Set wb = ActiveWorkbook&br&
strow = wst2.UsedRange.Rows.Count&br&&br&
If row1 = 0 Then&br&
wst2.Rows(&1:& & strow).Copy wst1.Cells(row1 + 1, 1)&br&
row1 = row1 + strow&br&
wst2.Rows(&2:& & strow).Copy wst1.Cells(row1 + 1, 1)&br&
row1 = row1 + strow - 1&br&
End If&br&
Application.CutCopyMode = False&br&
wb.Close (False)&br&
End If&br&Next&br&&br&MsgBox (&完成&)&br&&br&End Sub&br&&br&&br&&br&——————————————————————————————————————&br&&br&拆分or合并or群发邮件,是三个独立的宏,都可以灵活运用。建议大家复制保存为TXT文档或者存到一个excel里面,作为工具使用,不用每次黏贴复制了。&br&&br&最后&br&1、我是女生&br&2、我早就从那家公司离职了,平时工作忙和妹子没再联系,走之前给她写了一堆程序,覆盖她工作中50%的excel处理&br&3、只是同事之间的帮忙,而且我也喜欢研究。为什么要扯到感情,大家那么喜欢童话故事?&br&4、我不是专业写VBA的&br&&br&花了两个小时一个一个截图+写注释,你能不能点个赞再走n(*≧▽≦*)n
更新:建议下载文件,链接: 密码:0h3q ———————————————————————————————————————— 看到这个话题,我决定送给职场新人一个福利~~ 我刚毕业那会,Excel数据透视表都不会,后来进入…
已有帐号?
无法登录?
社交帐号登录
152 人关注
2595 人关注
866 条内容
589 人关注
393 条内容
388 条内容}

我要回帖

更多关于 pj 软件 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信