Python Sth

EasyDict

1
2
3
4
from easydict import EasyDict as edict
mydict = edict({})
mydict.foo = 3
print(mydict.foo) # 3

目录

检查目录,并生成一级目录

1
2
3
path = './xx/'
if os.path.isdir(path) == False:
os.mkdir(path)

多级目录生成

1
2
3
path = './xx/yy/zz/'
if not os.path.isdir(path):
os.makedirs(path)

R & W in TXT

ref

np.loadtxt()用于从文本加载数据。 文本文件中的每一行必须含有相同的数据。

1
loadtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)
  • fname:文件名
  • dtype:数据类型,默认float
  • comments:注释
  • delimiter:分隔符,默认是空格
  • skiprows:跳过前几行,0是第一行,必须int
  • usecols:要读取哪些列,0是第一列。例如,usecols = (1,4,5)将提取第2,第5和第6列。默认读取所有列。
  • unpack如果为True,将分列读取。
1
2
3
4
5
6
with open('odom.txt', 'r') as f:
data = f.readlines() #txt中所有字符串读入data
for line in data:
odom = line.split() #将单个数据分隔开存好
numbers_float = map(float, odom) #转化为浮点数

TXT追加内容

1
2
3
4
5
my_open = open(file_name, 'a')
#打开fie_name路径下的my_infor.txt文件,采用追加模式
#若文件不存在,创建,若存在,追加
my_open.write('xx\n')
my_open.close()

文件操作

文件移动

1
2
import shutil
shutil.move(src,des)

Print

pprint

it is used for pretty-print data structures.

Random

np.random.rand()

1
numpy.random.rand(d0,d1,…,dn)
  • rand函数根据给定维度生成[0,1)之间的数据,包含0,不包含1
  • dn为每个维度
  • 返回值为指定维度的数组

np.random.randn()

  • randn函数返回具有标准正态分布的数据。
  • dn为每个维度
  • 返回值为指定维度的数组

np.random.randint()

numpy.random.randint(low, high, size)

  • 返回开区间 [low, high)范围内的整数值
  • 默认high是None,如果只有low,那范围就是[0,low)。如果有high,范围就是[low,high)
  • size是输出数组的维度(形状),可以是列表,或者元组

np.random.choice()

numpy.random.choice(a, size)

  • a可以是一个数或者一个array,如果是一个数则sample范围是【0,a);如果是array,则从中sample
  • size为sample大小;如果size=(m,n,k),则采样$mnk$个。

String

数字补0

1
2
n = 123
number = "%05d"%n ### number = 00123

Plt

图片保存去除周边空白ref

1
2
3
plt.figure(figsize=(15,8))
p = plt.subplot(111)
plt.savefig('image_name', ,bbox_inches='tight')

bbox_inches =’tight’ 只能用于保存图片,不能用于显示。

Time

1
2
import time
start_time = time.time()

Zip

1
2
3
4
5
6
7
name = [ "Manjeet", "Nikhil", "Shambhavi", "Astha" ]
roll_no = [ 4, 1, 3, 2 ]
marks = [ 40, 50, 60, 70 ]
# using zip() to map values
mapped = zip(name, roll_no, marks)
# converting values to print as set
mapped = set(mapped)
1
The zipped result is : {('Shambhavi', 3, 60), ('Astha', 2, 70), ('Manjeet', 4, 40), ('Nikhil', 1, 50)}

How to unzip?
Unzipping means converting the zipped values back to the individual self as they were. This is done with the help of “*” operator.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
name = [ "Manjeet", "Nikhil", "Shambhavi", "Astha" ]
roll_no = [ 4, 1, 3, 2 ]
marks = [ 40, 50, 60, 70 ]
# using zip() to map values
mapped = zip(name, roll_no, marks)
# converting values to print as list
mapped = list(mapped)
# printing resultant values
print ("The zipped result is : ",end="")
print (mapped)
print("\n")
# unzipping values
namz, roll_noz, marksz = zip(*mapped)
print ("The unzipped result: \n",end="")
# printing initial lists
print ("The name list is : ",end="")
print (namz)
print ("The roll_no list is : ",end="")
print (roll_noz)
print ("The marks list is : ",end="")
print (marksz)
1
2
3
4
5
6
The zipped result is : [('Manjeet', 4, 40), ('Nikhil', 1, 50),
('Shambhavi', 3, 60), ('Astha', 2, 70)]
The unzipped result:
The name list is : ('Manjeet', 'Nikhil', 'Shambhavi', 'Astha')
The roll_no list is : (4, 1, 3, 2)
The marks list is : (40, 50, 60, 70)

Parser

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import argparse
parser = argparse.ArgumentParser(description="Process some parameters.")
parser.add_argument('--trainFeature', '-tf', type=int, required=True, default=1, help='train feature')
parser.add_argument('--trainInitial', '-ti', type=int, required=True, default=1,help='train initial')
parser.add_argument('--learningRate', '-lr', type=float, required=True, default=0.00001,help='learning rate')
parser.add_argument('--criticNum', '-cn', type=int, required=True, default=5,help='critic number')
parser.add_argument('--clipRange', '-cr', type=float, required=True,default=0.01, help='clip range')
args = parser.parse_args()
opts = {k:v for k,v in args._get_kwagrs()}
n_critic = args.criticNum
train_initial = args.trainInitial
train_feature = args.trainFeature
lr = args.learningRate
clip = args.clipRange
dgan = StageTwo(n_critic,train_initial,train_feature,lr,clip)
1
python xx.py -trainFeature 1 -trainInitial 1 -learningRate 0.001 -criticNum 5 -clipRange 0.01

Matplotlib

5 Quick and Easy Data Visualizations in Python with Code

8 of the best articles on visualizing data

ElementTree

!!!!!所有的输入都必须是字符串!!!!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def indent(elem, level=0):
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
def createXML():
root =ET.Element('annotation')
filename = ET.Element('filename')
filename.text = 'xx'
root.append(filename)
folder = ET.Element('folder')
folder.text = 'cad60/'
root.append(folder)
object = ET.Element('object')
root.append(object)
name = ET.SubElement(object,'name')
name.text = 'person'
action = ET.SubElement(object, 'action')
action.text = '12'
bndbox = ET.SubElement(object,'bndbox')
xmax = ET.SubElement(bndbox,'xmax')
xmax.text = '1'
xmin = ET.SubElement(bndbox, 'xmin')
xmin.text = '2'
ymax = ET.SubElement(bndbox, 'ymax')
ymax.text = '3'
ymin = ET.SubElement(bndbox,'ymin')
ymin.text = '4'
size = ET.Element('size')
root.append(size)
depth = ET.SubElement(size,'depth')
depth.text = '1'
height = ET.SubElement(size, 'height')
height.text = '2'
width = ET.SubElement(size, 'width')
width.text = '3'
indent(root)
tree = ET.ElementTree(root)
tree.write('wq.xml','utf-8')

creen Shot 2019-07-27 at 8.41.15 P

Naming style

ython-namin