Skip to content

Instantly share code, notes, and snippets.

@Halfish
Last active August 6, 2018 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Halfish/c6b445580fd1989aa60b to your computer and use it in GitHub Desktop.
Save Halfish/c6b445580fd1989aa60b to your computer and use it in GitHub Desktop.
Python常见语法笔录
import argparse
# this file shows how to use argparse
# step 1,默认构造器
parser = argparse.ArgumentParser()
# step 2, 必须输入的参数,只能在1,2,4中选一个
parser.add_argument("level", type=int, choices=[1, 2, 4], help="which level to print.")
# step 3, 可选参数,默认值为4
parser.add_argument("-l" , "--len", type=float, default=4, help="length of something.")
# step 4, 转换成变量
args = parser.parse_args()
print args
# 若运行 python argparse.py -h 可查看帮助
'''
usage: argparse.py [-h] [-l LEN] {1,2,4}
positional arguments:
{1,2,4} which level to print.
optional arguments:
-h, --help show this help message and exit
-l LEN, --len LEN length of something.
'''
# step 5, 添加二选一的选项 --verbose | --no-verbose
feature = parse.add_mutually_exclusive_group(required=False) # 互斥组
feature.add_argument("--verbose", dest='verbose', action='store_true', help="verbose")
feature.add_argument("--no-verbose", dest='verbose', action='store_false', help='no verbose')
parser.set_defaults=(feature=True) # 默认值为True,布尔值会存在args.verbose里
# 这样子的话,输出就会多一个像这样的选项啦! [-h] [--verbose | --no-verbose]
##################
# 1.从str到unicode
##################
# 方法A.一般Python内部对编码的处理,都是先转化成Unicode
b = u"风卷残云" #构建Unicode字符串
type(b) # <type 'unicode'>
# 方法B.除了直接用上面的u"Unicode编码",也可以调用unicode(str, encoding)函数
a = "我爱北京天安门" # a is <type 'str'>,纯ascii值,0~255的十六进制,'\xe6\x88...\xa8'
b = unicode(a, "utf8") # b转化成了 <type 'unicode'>,此时为Unicode编码,u'\u6211\u7231...\u95e8'
# 方法C.字符串str类型有decode函数,可以转化成Unicode
b = a.decode("utf-8") # 其实和unicode(a, 'utf-8')函数功能一样
##########################
# 2.从unicode编码成str类型
##########################
c = b.encode("utf8") # 调用Unicode的函数encode,可以转化成相应编码的字符串
type(c) # <type 'str'>
print(c) # 我爱北京天安门,c其实就是,'\xe6\x88...\xa8',和上面的a是一样的。
# read file
with open('path/to/file.py', 'r') as f:
print(f.read()) # or print(f.readlines())
# list all the file in a directory
import os
files = os.listdir('./pic/')
# make new directory
import os
if not os.path.isdir('./pic'):
os.mkdir('./pic')
# split a fullname
filename, extname = os.path.splitext('./pic/5.jpg') # filename, extname = ('./pic/5', '.jpg')
import json
jsonstring = json.dumps({'name':'bruce', 'age':24})
jsonarray = json.loads('[8, "books"]')
type(jsonstring)
type(jsonarray)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment