StandardLib

StandardLib Text Processing Services re 正则表达式 import re # 编译 datepat = re.compile(r'\d+/\d+/\d+') # 匹配 text1 = '11/27/2012' if datepat.match(text1): print('yes') # 搜索 text = 'Today is 11/27/2012. PyCon starts 3/13/2013.' datepat.findall(text) # ['11/27/2012', '3/13/2013'] # 通常会分组匹配 datepat = re.compile(r'(\d+)/(\d+)/(\d+)') m = datepat.match('11/27/2012') print(m.group(0), m.group(1), m.group(2), m.group(3), m.groups()) datepat.findall(text) # [('11', '27', '2012'), ('3', '13', '2013')] # 返回迭代 for m in datepat.finditer(text): print(m.groups()) # 只是一次匹配/搜索操作的话可以无需先编译 re.findall(r'(\d+)/(\d+)/(\d+)', text) # 替换 re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text) # 'Today is 2012-11-27. PyCon starts 2013-3-13.' re.sub(r'(?P<month>\d+)/(?P<day>\d+)/(?P<year>\d+)', r'\g<year>-\g<month>-\g<day>', text) # 命名分组 Data Types datetime from datetime import datetime a = datetime(2012, 9, 23) # 时间转字符串 a.strftime('%Y-%m-%d') # 字符串转时间 text = '2012-09-20' y = datetime.strptime(text, '%Y-%m-%d') zoneinfo (3.9+) from datetime import datetime from zoneinfo import ZoneInfo # Create a datetime object without timezone naive_dt = datetime.now() # Add the timezone to the datetime object aware_dt = naive_dt.replace(tzinfo=ZoneInfo('Asia/Shanghai')) print(aware_dt) collections nametuple from collections import nametuple # namedtuple(typename, field_names) Point = namedtuple('Point', ['x', 'y']) p = Point(x=11, y=22) print(p.x + p.y) deque from collections import deque d = deque(["a", "b", "c"]) d.append("f") # add to the right side d.appendleft("z") # add to the left side e = d.pop() # pop from the right side e = d.popleft() # pop from the left side d = deque(maxlen=10) # deque with max length, FIFO Counter collections — Container datatypes ...

January 1, 2000

Visualization

Matplotlib Basic Import from matplotlib import pyplot as plt Build figure fig = plt.figure(1) fig = plt.figure(1, figsize=(10,10)) # set figure size Tighten the layout fig.tight_layout() Build subplots ax = plt.subplot(111) ax = plt.subplot(211) # build two subplots and select the left one ax = plt.subplot(111, projection='polar') # build polar subplot Draw graphs ax.plot() ax.bar() ax.hist() ax.scatter() ax.plot_date() Show figure fig.show() Clear figure fig.clf() Save figure plt.savefig('path/name.png') Legend & Label & Tick & Grid # title ax.set_title('plot', fontsize=20) # label ax.set_xlabel('Threshold (m/s)') ax.set_ylabel('Strom periods (hours)') # ticks ax.set_xticks(np.arange(0, 1.1, 0.1)) ax.set_yticks(np.arange(0, 1.1, 0.1)) ax.set_xticklabels(labels, size=9, rotation=15) # axis limits plt.xlim(0, 1) # or ax.set_xlim(0, 1) # grid ax.grid(True) ax.grid(False) ax.yaxis.grid(True) # legend ax.plot(xx, yy, label='plot1') ax.legend(loc='lower left', frameon=False, fontsize=12) # or ax.legend(['line1', 'line2']) Two y-axis ...

January 1, 2000