复制文件的函数在os模块中不存在。原因是复制文件并非由操作系统提供的系统调用。shutil模块提供了copyfile()函数,可以看做是os模块的补充。删除import os import shutil base_path = os.path.dirname(__file__) path = os.path.join(base_path, 'img') ## 删除文件夹 shutil.rmtree(path)拷贝## 拷贝文件夹 shutil.copytree("./img","./img2") src = os.path.abspath(__file__) dst = os.path.join(os.path.dirname(__file__), "aaa.py") ## 文件到文件的拷贝,其中dst必须是文件 shutil.copyfile(src, dst) ## 文件拷贝,src必须是文件,dst可以是文件或者目录 shutil.copy(src, dst) ## 同上,但是拷贝的文件带着原有属性,类似于L
元字符匹配单字符匹配:字符功能.匹配任意字符,除了\n[]匹配[]中列举的字符\d匹配数字,相当于[0-9]\D匹配非数字\s匹配空白,即空格、tab键\S匹配非空白\w匹配单词字符,即任意字母数字下划线\W匹配非单词字符数量匹配:字符功能*0或多个,相当于{0,}+至少一个,相当于{1,}?0或1个,相当于{0,1}{m}匹配前一个规则的字符出现m次边界匹配:字符功能^匹配字符串开头$匹配字符串结尾\b匹配单词边界\B匹配非单词边界分组匹配:字符功能``匹配左右任意一个表达式()将括号中字符作为一个分组findall()匹配字符串中所有符合正则的内容(都没找到返回空列表[])。import re s = '我的号码是:10086,你的号码是10010' list = re.findall(r'\d+', s, re.S) print(list) # ['10086', '10010']字符串的r标记,表示当前字符串是原始字符串,即内部的转义字符无效而是普通字符。re.S的作用是让findall()函数在查找时可以自动考虑换行的影响,使得非贪婪匹配可以匹配换行。re模块中的标志还有:
推导式是Python中提供的一个非常方便的功能,可以通过一行代码实现创建list、dict、tuple、set 的同时初始化一些值。num_list = [ i for i in range(5)] # 列表 print(num_list) # 结果为:[0, 1, 2, 3, 4] num_set = { i for i in range(5)} # 集合 print(num_set) # 结果为:{0, 1, 2, 3, 4} num_dict = { i:i for i in range(5)} # 字典 print(num_dict) # 结果为:{0: 0, 1: 1, 2: 2, 3: 3, 4: 4} data = (i for i in range(5)) # 元组 print(data) # 结果为:<generator object <genexpr> at 0x00000> for item in data: print(item)元组不同于其他类型,不会立即执行内部循环去生成数据,而是得到一个生成器。嵌套## 生成一副扑克牌
读写文件就是请求操作系统打开一个文件对象(通常称为文件描述符),然后,通过操作系统提供的接口从这个文件对象中读取数据(读文件),或者把数据写入这个文件对象(写文件)。pathlib模块用模块pathlib来处理文件,是一种更加简单的文件读写方法。from pathlib import Path path = Path("pi_million_digits.txt") contents = path.read_text(encoding="utf-8") lines = contents.splitlines() pi_string = "" for line in lines: pi_string += line.lstrip() birthday = input("Enter your birthday, in the form mmddyy: ") if birthday in pi_string: print("Your birthday appears in the
名单姓名性别身份张三女嘉宾李四男媒体王五男嘉宾实现代码from docx import Document # 创建文档 from docx.oxml.ns import qn # 中文 from docx.enum.text import WD_PARAGRAPH_ALIGNMENT # 段落 from docx.shared import Pt, RGBColor, Mm, Cm # 大小磅数/字号 from openpyxl import load_workbook def template(name, sex, types): """ 创建模板 - 先生/女士 - 嘉宾/媒体 """ word = Document() # 创建word文档对象 word.styles['Normal'].font.name = u'微软雅黑' word.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia
Vue 中的指令按照不同的用途可分为6大类:内容渲染指令属性绑定指令事件绑定指令双向绑定指令条件渲染指令列表渲染指令内容渲染内容渲染指令用来辅助开发者渲染 DOM 元素的文本内容。常见的内容渲染指令有3个:v-text、{{ }}、v-html。v-text会覆盖掉元素里面的内容。{{ }}专业名称是插值表达式(Mustache),专门用来解决 v-text 会覆盖默认文本内容的问题。插值表达式可以使用过滤器:<div id="app"> <p>{{message | capitalize}}</p> </div> <script> const app = new Vue({ el: "#app", data: { message: "i love vue!", }, filters: { capitalize(str) { return str.charAt(0).toUpperCase
环境搭建(Windows)创建虚拟环境virtualenv django_env django_envScriptsactivate # 激活虚拟环境 django_envScriptsdeactivate # 退出依赖包安装pip install django pip install djangorestframework pip install PymySQL pip install pillow pip install django-redis pip list # 查看虚拟环境中安装的包 pip freeze > requirements.txt # 收集当前环境中安装的包及其版本 pip install -r requirements.txt # 安装项目使用到的模块项目搭建mkdir django cd django django-admin startproject siteapi使用PyCharm打开新建的项目siteapi,点击 「File」->「Settings」->「Project: siteapi」->「Python Interpret
基本介绍NumPy:Numerical Python的缩写,提供了底层基于C语言实现的数值计算库,与Python内置的list数据结构相比,其支持更加规范的数据类型和极其丰富的操作接口,速度也更快。安装NumPyNumPy是第三方库,所以在使用前必须先安装NumPy。可以使用pip命令安装:pip install numpy。安装完就可以写NumPy代码了。一般流程是先import numpy,为了后续调用方便,通常在import完之后,还给它一个缩写形式as np。创建NumPy数组ndarrayNumPy默认ndarray所有元素的类型是相同的。如果传进来的列表中包含不同的类型,则统一为同一类型,优先级:str > float > int。使用np.array()import numpy as np n = np.array([1, 2, 3]) print(n.shape) # 形状:(3,)使用np.ones()创建一个所有元素都为1的多维数组。n = np.ones((3, 2), dtype=np.int8) # 默认是float类型 print(n.sh
Glitch Text Generator文本特效,可以选择在文本的顶部 / 中部 / 尾部添加乱码特效,效果:h́t́̽̿ẗ́p͋̆̈́s͌:̏/̂̀̋/̊͝ä̋͊b̿̓o̓s̒s̛̎.̇͝t̀̂͝o̓p̓/͂͌͌Glitch文本生成器可以为您的数字项目轻松创建令人惊叹的小故障文本效果。网站地址Glitch Text Generator:https://glitchtext.net/
背景知识单元测试在开发过程中非常有必要,它可以验证实现的一个函数是否达到预期。使用单元测试能提高开发效率,也更规范。官方文档:https://code.visualstudio.com/docs/python/testing单元测试在VS Code中,可以实现对编写的每一个函数进行单元测试,理应每实现一个函数都有一个单元测试的用例。演示配置测试文件点击VS Code左边栏的测试,配置Python测试文件,依次选择:Configure Python Tests -> unittest -> . Root directory -> test*.py。这里表示使用unittest框架测试,测试文件的格式为test*.py。随后在项目目录中多了一个.vscode文件夹,其中包含一个settings.json文件,在这里可以设置项目的一些配置。新建一个Python项目TestNumpy.py测试文件的格式为test*.py。import numpy as np from unittest import TestCase class TestNumpy(TestCase):
在Python中:一个py文件,模块(module)含有多个py文件的文件夹,包(package)在包中有一个默认内容为空的__init__.py文件,一般用于描述当前包的信息(在导入包下面的模块时,会自动加载)。导入导入,其实就是将模块或包加载到内存中,以后再去内存中拿就行。在Python内部默认设置了一些路径,导入模块或包时,都会按照指定顺序逐一去特定的路径查找。如果想要导入任意的模块或包,可以手动在sys.path中添加指定路径,然后再导入,例如:import sys sys.path.append("指定路径") import xxx # 导入指定路径下的一个xxx.py文件主文件执行一个py文件时:__name__ == "__main__"导入一个py文件时:__name__ == "模块名"搜索顺序导入模块时,先搜索当前目录指定模块名的文件,如果有就直接导入;如果没有,再搜索系统目录。模块一般都有一个内置属性__file__,可查看模块的完整路径。__init__.py要在外界使用包中的模块,需在__init_
录制录制的命令为codegen,命令行输入后会自动打开浏览器,然后可以看见在浏览器上的一举一动都会被自动翻译成代码:python -m playwright codegen --target python -o my.py -b webkit https://www.baidu.com/参数含义:-o:将录制的脚本保存到文件--target:规定生成脚本的语言,有JS和Python两种,默认为Python-b:指定浏览器驱动,chromium、firefox、webkit
OS(operating system)是Python内置模块,提供与操作系统相关的方法。import os print(os.name) # 操作系统类型 print(os.environ) # 操作系统中定义的环境变量 print(os.environ.get("PATH")) # 获取某个环境变量的值如果是posix,说明系统是Linux、Unix或Mac OS X,如果是nt,说明是Windows系统。文件操作重命名文件# abc.txt -> 123.txt os.rename('abc.txt', '123.txt')删除文件# 删除文件或文件夹 os.removedirs(p1) # 删除空文件夹 if os.path.exists(p2): os.remove(p2) # 文件不存在会报错判断# 是否是文件 is_file = os.path.isfile('abc.txt') print(is_file) # True目录操作目录列表dirs = os.listdir(p1) # 获取所有文件和文件夹 # 获取所有文件和文件夹
from openpyxl import workbook # excel文件 & sheet wb = workbook.Workbook() sheet = wb.worksheets[0] # sheet = wb.active # 找到单元格(行,列),写入值 cell = sheet.cell(1, 1) cell.value = '李小龙' wb.save('info.xlsx')读取Excelfrom openpyxl import load_workbook wb = load_workbook('abc.xlsx') sheet = wb['Sheet1'] # sheet.rows返回一个生成器对象,用推导列表把对象取出来放list里 rows = [x for x in sheet.rows] # 从第二行开始取值 for i in rows[1:]: print(i[0].value, i[1].value, i[2].value)
这个库可在命令行中向程序传入参数并让程序运行。import argparse def main(): parser = argparse.ArgumentParser(description="Demo of argparse") parser.add_argument('-n', '--name', default='Li', help="Enter the name") args = parser.parse_args() print(args) name = args.name print('Hello {}'.format(name)) if __name__ == '__main__': main()首先导入argparse包,然后通过argparse.ArgumentParser生成对象,description是在命令行模式时显示帮助信息之后通过parser.add_argument向该对象中添加命令行参数和选项最后使用parser.parse_args进行解析add_arg
环境初始化(CentOS)## 安装wget,参数-y会自动选择y,全自动 yum -y install wget ## 下载阿里云源,-O选项以其他名称保存下载的文件 wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo # 基础仓库 wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo # 额外仓库 ## 清空本地缓存 yum clean all ## 生成新的缓存 yum makecache ## 清空现有规则来暂时停止防火墙(警告:这只适合在没有配置防火墙的环境中,如果已经配置过默认规则为deny的环境,此步骤将使系统的所有网络访问中断) iptables -F ## 查看是否开启了SELinux,确保是disabled的状态 getenforce ## 临时关闭SELinux setenforce 0 ## 永久关闭SELinux,SELINUX=e
import urllib.parse as parse res = parse.quote("中文", encoding="UTF-8") res2 = parse.unquote("%E4%B8%AD%E6%96%87", encoding="UTF-8") print(res) # %E4%B8%AD%E6%96%87 print(res2) # 中文
因服务器不在国内的缘故,网站没有很好的速度,所以苦苦钻研加速之道。Github创建Github仓库登录到Github之后点击右上角头像旁边的「+」,选择new repository创建新仓库在仓库创建页面 ,填写仓库名,其他默认就行通过Git同步到Github进入要托管的网站目录,创建.gitignore文件(https://www.toptal.com/developers/gitignore):cd 站点目录 touch .gitignore vi .gitignore把以下内容复制到.gitignore:## 排除文件目录 *.php *.html *.xml *.po *.mo *.json *.txt *.htaccess *.zip *.gz *.phtml *.html.gz *.bmp *.md !/wp-content/cache/ !/wp-content/upload/通过Git同步静态文件到Github:git init #初始化git git add -A wp-content wp-includes .gitignore # 添加要上传的文件 git com
RMySQL先安装依赖包:sudo yum install mariadb-devel sudo yum install mysql-devel在安装RMySQL:install.packages('RMySQL')RCurl和curl直接安装可能会报错,需要先执行:sudo yum -y install curl sudo yum -y install libcurl libcurl-devel sudo yum -y install libxml2 libxml2-devel然后再安装RCurl和curl:sudo su - -c "R -e "install.packages('RCurl', repos='https://cran.rstudio.com/')"" sudo su - -c "R -e "install.packages('curl', repos='https://cran.rstudio.com/')""
CentOS 7自带的Python版本是Python 2.7,想用Python 3就需要手动安装,并且配置后才可以并存使用。查看Python在哪儿whereis python cd /usr/bin/ ll python*可以看到Python在/usr/bin目录中,python指向python2,python2指向python2.7,因此我们可以装个python3,然后将python指向python3,那么两个版本的python就能共存了。通过yum安装这种方式安装,简单高效、无需配置环境变量、但是最高支持3.6.8版本。安装命令:yum install python3 -y卸载命令:yum remove python3 -y安装pip:python3 -m pip install --upgrade pip手动编译安装首先安装安装gcc编译器:yum install gcc -y接着运行以下命令,安装编译Python 3需用到的相关依赖:yum -y install openssl-devel libffi-devel bzip2-devel yum -y groupinstall
CentOS 7下,pip没有设置的话,在命令行输入pip --version,指向的是python2。安装好Python 3后,里面就已经下载好了pip3,我们只需要把pip指向python3即可。cd /usr/bin ll pip* ## 删除pip文件 rm pip ## 重新设置pip文件 ln -s /usr/local/python3/bin/pip3 /usr/bin/pip ## 补加pip3命令 ln -s /usr/local/python3/bin/pip3 /usr/bin/pip3 此时输入命令pip --version或者pip3 --version会发现pip已经指向python3了。以后下载python3的库,直接使用命令,pip3 install或pip install,而下载python2的库,使用命令pip2 install。
三毛
头发渐少,仅剩三根