8个Python 实用脚本

做了那么多年开发,自学了很多门编程语言,我很明白学习资源对于学一门新语言的重要性,这些年也收藏了不少的Python干货,对我来说这些东西确实已经用不到了,但对于准备自学Python的人来说,或许它就是一个宝藏,可以给你省去很多的时间和精力。

别在网上瞎学了,我最近也做了一些资源的更新,只要你是我的粉丝,这期福利你都可拿走。

我先来介绍一下这些东西怎么用,文末抱走。


(1)Python所有方向的学习路线(新版)

这是我花了几天的时间去把Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。

最近我才对这些路线做了一下新的更新,知识体系更全面了。

在这里插入图片描述

(2)Python学习视频

包含了Python入门、爬虫、数据分析和web开发的学习视频,总共100多个,虽然没有那么全面,但是对于入门来说是没问题的,学完这些之后,你可以按照我上面的学习路线去网上找其他的知识资源进行进阶。

在这里插入图片描述

(3)100多个练手项目

我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了,只是里面的项目比较多,水平也是参差不齐,大家可以挑自己能做的项目去练练。

在这里插入图片描述

(4)200多本电子书

这些年我也收藏了很多电子书,大概200多本,有时候带实体书不方便的话,我就会去打开电子书看看,书籍可不一定比视频教程差,尤其是权威的技术书籍。

基本上主流的和经典的都有,这里我就不放图了,版权问题,个人看看是没有问题的。

(5)Python知识点汇总

知识点汇总有点像学习路线,但与学习路线不同的点就在于,知识点汇总更为细致,里面包含了对具体知识点的简单说明,而我们的学习路线则更为抽象和简单,只是为了方便大家只是某个领域你应该学习哪些技术栈。

在这里插入图片描述

(6)其他资料

还有其他的一些东西,比如说我自己出的Python入门图文类教程,没有电脑的时候用手机也可以学习知识,学会了理论之后再去敲代码实践验证,还有Python中文版的库资料、MySQL和HTML标签大全等等,这些都是可以送给粉丝们的东西。

在这里插入图片描述

这些都不是什么非常值钱的东西,但对于没有资源或者资源不是很好的学习者来说确实很不错,你要是用得到的话都可以直接抱走,关注过我的人都知道,这些都是可以拿到的。

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

4.将源目录240天以上的所有文件移动到目标目录。

import shutil

import sys

import time

import os

import argparse

usage = ‘python move_files_over_x_days.py -src [SRC] -dst [DST] -days [DAYS]’

description = ‘Move files from src to dst if they are older than a certain number of days. Default is 240 days’

args_parser = argparse.ArgumentParser(usage=usage, description=description)

args_parser.add_argument(‘-src’, ‘–src’, type=str, nargs=‘?’, default=‘.’, help=‘(OPTIONAL) Directory where files will be moved from. Defaults to current directory’)

args_parser.add_argument(‘-dst’, ‘–dst’, type=str, nargs=‘?’, required=True, help=‘(REQUIRED) Directory where files will be moved to.’)

args_parser.add_argument(‘-days’, ‘–days’, type=int, nargs=‘?’, default=240, help=‘(OPTIONAL) Days value specifies the minimum age of files to be moved. Default is 240.’)

args = args_parser.parse_args()

if args.days < 0:

args.days = 0

src = args.src # 设置源目录

dst = args.dst # 设置目标目录

days = args.days # 设置天数

now = time.time() # 获得当前时间

if not os.path.exists(dst):

os.mkdir(dst)

for f in os.listdir(src): # 遍历源目录所有文件

if os.stat(f).st_mtime < now - days * 86400: # 判断是否超过240天

if os.path.isfile(f): # 检查是否是文件

shutil.move(f, dst) # 移动文件

5.扫描脚本目录,并给出不同类型脚本的计数。

import os

import shutil

from time import strftime

logsdir=“c:\logs\puttylogs”

zipdir=“c:\logs\puttylogs\zipped_logs”

zip_program=“zip.exe”

for files in os.listdir(logsdir):

if files.endswith(“.log”):

files1=files+“.”+strftime(“%Y-%m-%d”)+“.zip”

os.chdir(logsdir)

os.system(zip_program + " " + files1 +" "+ files)

shutil.move(files1, zipdir)

os.remove(files)

6.下载Leetcode的算法题。

‘’’

遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333

寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!

‘’’

import sys

import re

import os

import argparse

import requests

from lxml import html as lxml_html

try:

import html

except ImportError:

import HTMLParser

html = HTMLParser.HTMLParser()

try:

import cPickle as pk

except ImportError:

import pickle as pk

class LeetcodeProblems(object):

def get_problems_info(self):

leetcode_url = ‘https://leetcode.com/problemset/algorithms’

res = requests.get(leetcode_url)

if not res.ok:

print(‘request error’)

sys.exit()

cm = res.text

cmt = cm.split(‘tbody>’)[-2]

indexs = re.findall(r’(\d+)', cmt)

problem_urls = [‘https://leetcode.com’ + url \

for url in re.findall(

r’<a href=“(/problems/.+?)”', cmt)]

levels = re.findall(r"(.+?)", cmt)

tinfos = zip(indexs, levels, problem_urls)

assert (len(indexs) == len(problem_urls) == len(levels))

infos = []

for info in tinfos:

res = requests.get(info[-1])

if not res.ok:

print(‘request error’)

sys.exit()

tree = lxml_html.fromstring(res.text)

title = tree.xpath(‘//meta[@property=“og:title”]/@content’)[0]

description = tree.xpath(‘//meta[@property=“description”]/@content’)

if not description:

description = tree.xpath(‘//meta[@property=“og:description”]/@content’)[0]

else:

description = description[0]

description = html.unescape(description.strip())

tags = tree.xpath(‘//div[@id=“tags”]/following::a[@class=“btn btn-xs btn-primary”]/text()’)

infos.append(

{

‘title’: title,

‘level’: info[1],

‘index’: int(info[0]),

‘description’: description,

‘tags’: tags

}

)

with open(‘leecode_problems.pk’, ‘wb’) as g:

pk.dump(infos, g)

return infos

def to_text(self, pm_infos):

if self.args.index:

key = ‘index’

elif self.args.title:

key = ‘title’

elif self.args.tag:

key = ‘tags’

elif self.args.level:

key = ‘level’

else:

key = ‘index’

infos = sorted(pm_infos, key=lambda i: i[key])

text_template = ‘## {index} - {title}\n’ \

{level} {tags}\n’ \

‘{description}\n’ + ‘\n’ * self.args.line

text = ‘’

for info in infos:

if self.args.rm_blank:

info[‘description’] = re.sub(r’[\n\r]+‘, r’\n’, info[‘description’])

text += text_template.format(**info)

with open(‘leecode problems.txt’, ‘w’) as g:

g.write(text)

def run(self):

if os.path.exists(‘leecode_problems.pk’) and not self.args.redownload:

with open(‘leecode_problems.pk’, ‘rb’) as f:

pm_infos = pk.load(f)

else:

pm_infos = self.get_problems_info()

print(‘find %s problems.’ % len(pm_infos))

self.to_text(pm_infos)

def handle_args(argv):

p = argparse.ArgumentParser(description=‘extract all leecode problems to location’)

p.add_argument(‘–index’, action=‘store_true’, help=‘sort by index’)

p.add_argument(‘–level’, action=‘store_true’, help=‘sort by level’)

p.add_argument(‘–tag’, action=‘store_true’, help=‘sort by tag’)

p.add_argument(‘–title’, action=‘store_true’, help=‘sort by title’)

p.add_argument(‘–rm_blank’, action=‘store_true’, help=‘remove blank’)

p.add_argument(‘–line’, action=‘store’, type=int, default=10, help=‘blank of two problems’)

p.add_argument(‘-r’, ‘–redownload’, action=‘store_true’, help=‘redownload data’)

args = p.parse_args(argv[1:])

return args

def main(argv):

args = handle_args(argv)

x = LeetcodeProblems()

x.args = args

x.run()

if name == ‘main’:

argv = sys.argv

main(argv)

7.将 Markdown 转换为 HTML。

import sys

import os

from bs4 import BeautifulSoup

import markdown

class MarkdownToHtml:

headTag = ‘’

def init(self,cssFilePath = None):

if cssFilePath != None:

self.genStyle(cssFilePath)

def genStyle(self,cssFilePath):

with open(cssFilePath,‘r’) as f:

cssString = f.read()

self.headTag = self.headTag[:-7] + ‘’.format(cssString) + self.headTag[-7:]

def markdownToHtml(self, sourceFilePath, destinationDirectory = None, outputFileName = None):

if not destinationDirectory:

未定义输出目录则将源文件目录(注意要转换为绝对路径)作为输出目录

destinationDirectory = os.path.dirname(os.path.abspath(sourceFilePath))

if not outputFileName:

未定义输出文件名则沿用输入文件名

outputFileName = os.path.splitext(os.path.basename(sourceFilePath))[0] + ‘.html’

if destinationDirectory[-1] != ‘/’:

destinationDirectory += ‘/’

with open(sourceFilePath,‘r’, encoding=‘utf8’) as f:

markdownText = f.read()

编译出原始 HTML 文本

rawHtml = self.headTag + markdown.markdown(markdownText,output_format=‘html5’)

格式化 HTML 文本为可读性更强的格式

beautifyHtml = BeautifulSoup(rawHtml,‘html5lib’).prettify()

with open(destinationDirectory + outputFileName, ‘w’, encoding=‘utf8’) as f:

f.write(beautifyHtml)

if name == “main”:

mth = MarkdownToHtml()

做一个命令行参数列表的浅拷贝,不包含脚本文件名

argv = sys.argv[1:]

目前列表 argv 可能包含源文件路径之外的元素(即选项信息)

程序最后遍历列表 argv 进行编译 markdown 时,列表中的元素必须全部是源文件路径

outputDirectory = None

if ‘-s’ in argv:

cssArgIndex = argv.index(‘-s’) +1

cssFilePath = argv[cssArgIndex]

检测样式表文件路径是否有效

if not os.path.isfile(cssFilePath):

print('Invalid Path: '+cssFilePath)

sys.exit()

mth.genStyle(cssFilePath)

pop 顺序不能随意变化

argv.pop(cssArgIndex)

argv.pop(cssArgIndex-1)

if ‘-o’ in argv:

dirArgIndex = argv.index(‘-o’) +1

outputDirectory = argv[dirArgIndex]

检测输出目录是否有效

if not os.path.isdir(outputDirectory):

print('Invalid Directory: ’ + outputDirectory)

sys.exit()

pop 顺序不能随意变化

argv.pop(dirArgIndex)

argv.pop(dirArgIndex-1)

至此,列表 argv 中的元素均是源文件路径

遍历所有源文件路径

for filePath in argv:

判断文件路径是否有效

if os.path.isfile(filePath):

mth.markdownToHtml(filePath, outputDirectory)

else:

print('Invalid Path: ’ + filePath)

8.文本文件编码检测与转换。

import sys

import os

import argparse

from chardet.universaldetector import UniversalDetector

parser = argparse.ArgumentParser(description = ‘文本文件编码检测与转换’)

parser.add_argument(‘filePaths’, nargs = ‘+’,

help = ‘检测或转换的文件路径’)

parser.add_argument(‘-e’, ‘–encoding’, nargs = ‘?’, const = ‘UTF-8’,

help = ‘’’

目标编码。支持的编码有:

ASCII, (Default) UTF-8 (with or without a BOM), UTF-16 (with a BOM),

UTF-32 (with a BOM), Big5, GB2312/GB18030, EUC-TW, HZ-GB-2312, ISO-2022-CN, EUC-JP, SHIFT_JIS, ISO-2022-JP,

ISO-2022-KR, KOI8-R, MacCyrillic, IBM855, IBM866, ISO-8859-5, windows-1251, ISO-8859-2, windows-1250, EUC-KR,

ISO-8859-5, windows-1251, ISO-8859-1, windows-1252, ISO-8859-7, windows-1253, ISO-8859-8, windows-1255, TIS-620

‘’')

parser.add_argument(‘-o’, ‘–output’,

help = ‘输出目录’)

解析参数,得到一个 Namespace 对象

args = parser.parse_args()

输出目录不为空即视为开启转换, 若未指定转换编码,则默认为 UTF-8

if args.output != None:

if not args.encoding:

默认使用编码 UTF-8

args.encoding = ‘UTF-8’

检测用户提供的输出目录是否有效

if not os.path.isdir(args.output):

print('Invalid Directory: ’ + args.output)

sys.exit()

else:

if args.output[-1] != ‘/’:

args.output += ‘/’

实例化一个通用检测器

detector = UniversalDetector()

print()

print(‘Encoding (Confidence)’,‘:’,‘File path’)

for filePath in args.filePaths:

检测文件路径是否有效,无效则跳过

if not os.path.isfile(filePath):

print('Invalid Path: ’ + filePath)

continue

重置检测器

detector.reset()

以二进制模式读取文件

for each in open(filePath, ‘rb’):

检测器读取数据

detector.feed(each)

若检测完成则跳出循环

if detector.done:

break

关闭检测器

detector.close()

读取结果

charEncoding = detector.result[‘encoding’]

confidence = detector.result[‘confidence’]

打印信息

if charEncoding is None:

charEncoding = ‘Unknown’

confidence = 0.99

print(‘{} {:>12} : {}’.format(charEncoding.rjust(8),

‘(’+str(confidence*100)+‘%)’, filePath))

if args.encoding and charEncoding != ‘Unknown’ and confidence > 0.6:

若未设置输出目录则覆盖源文件

outputPath = args.output + os.path.basename(filePath) if args.output else filePath

with open(filePath, ‘r’, encoding = charEncoding, errors = ‘replace’) as f:

现在能在网上找到很多很多的学习资源,有免费的也有收费的,当我拿到1套比较全的学习资源之前,我并没着急去看第1节,我而是去审视这套资源是否值得学习,有时候也会去问一些学长的意见,如果可以之后,我会对这套学习资源做1个学习计划,我的学习计划主要包括规划图和学习进度表。

分享给大家这份我薅到的免费视频资料,质量还不错,大家可以跟着学习

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值