1、python中的format格式拼接字符串

1
2
3
4
5
d = {'a': 1, 'b': 2, 'c': 3, 'd': 5}

print('{a},{b}'.format(**d))
print('{0},{1},{0}'.format('a', 'b'))
print(f"{d['a']}")

输出:

1
2
3
1,2
a,b,a
1

2、python控制台输出带颜色的文字方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#格式:  设置颜色开始 :\033[显示方式;前景色;背景色m
#说明:
前景色 背景色 颜色
---------------------------------------
30 40 黑色
31 41 红色
32 42 绿色
33 43 黃色
34 44 蓝色
35 45 紫红色
36 46 青蓝色
37 47 白色
显示方式 意义
-------------------------
0 终端默认设置
1 高亮显示
4 使用下划线
5 闪烁
7 反白显示
8 不可见

#例子:
\033[1;31;40m <!--1-高亮显示 31-前景色红色 40-背景色黑色-->
\033[0m <!--采用终端默认设置,即取消颜色设置-->
1
2
3
4
例子
print('紫红字体 \033[1;35m hello world \033[0m!')
print('褐色背景绿色字体 \033[1;32;43m hello world \033[0m!')
print('\033[1;33;44mhello world\033[0m')

在这里插入图片描述

3、控制台输出白色方框

1
print('█')

4、有序字典

1
2
3
4
5
6
7
8
9
import collections

d1 = collections.OrderedDict() # 创建一个有序字典
d1['a'] = 'A'
d1['b'] = 'B'
d1['c'] = 'C'
d1['d'] = 'D'
for k, v in d1.items():
print(k, v)

5、Python在Windows系统下实现TTS(文字转语音)

导入包:

1
2
3
4
5
6
pip install pypiwin32

import win32com.client
spk = win32com.client.Dispatch("SAPI.SpVoice")
spk.Speak(u"my name is ldc,what is your name")
spk.Speak(u"大家好")

6、定义一个简单闹钟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# pip install pypiwin32 -i https://pypi.python.org/simple
import win32com.client
import time
import winsound

spk = win32com.client.Dispatch("SAPI.SpVoice")
# 定义闹钟时间
clocktime = [[19, 19], [11, 10], [12, 10], [18, 47]]
runinghour = 1 # 定义运行时间
times = runinghour * 3600 # 次数
print(times)
for i in range(1, times):
time_now = [time.localtime(time.time()).tm_hour, time.localtime(time.time()).tm_min]
if time_now in clocktime:
print(time_now)
winsound.Beep(1000, 1000)
spk.Speak(u"快去看下饭好了没有?")
time.sleep(60) # 每分钟对比一次时间

7、根据年月获取当月天数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def get_month_days(year, month):
"""
根据年份,月份信息显示此月份天数
:param year: 年份:
:param month: 月份(1~12):
:return: 当月天数
"""
if month >12 or month <= 0:
return -1
if month == 2:
return 29 if year % 4 == 0 and year % 100 != 0 or year % 400 == 0 else 28

if month in (4, 6, 9, 11):
return 30
else:
return 31

a = '2020-04'.split('-')
year = int(a[0])
month = int(a[1])
print(get_month_days(year,month))

输出:
30

8、获取当前时间月份的首日与最后一天

1
2
3
4
5
6
7
8
9
10
11
12
import calendar

def get_month_start_and_end(date=datetime.datetime.now()):
"""
获取当前时间的月份首日与最后一天
:param date:
:return: (首日,最后一天)
"""
year, month = str(date).split('-')[0], str(date).split('-')[1]
end = calendar.monthrange(int(year), int(month))[1]
return f'{year}-{month}-01', f'{year}-{month}-{end}'

9、 二维列表、二维数组行求和与列求和

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import pandas as pd
from functools import reduce

# 二维数组,对列和行求和
a = [
['', 0, '', 1, 4.1],
['', 0, '', '', 4],
['123', 0, '', 3, 4, 6,7],
]


def aa(x, y):
x = 0 if isinstance(x, str) else x
y = 0 if isinstance(y, str) else y
return x + y

# 对行求和
row_sum = [reduce(aa, i) for i in a]
# 对列求和,只能处理相同长度的子元素
column_sum_1 = [reduce(aa, i) for i in zip(*a)]
# 对列求和,可以处理不同长度的子元素
column_sum_2 = list(dict(pd.DataFrame(a).fillna(0).apply(lambda x: '' if any(isinstance(d, str) for d in x) else round(x.sum(), 2))).values())
print('行求和:{}\r\n列求和(相同长度):{}\r\n列求和:{}'.format(row_sum, column_sum_1, column_sum_2))

输出:

1
2
3
行求和:[5.1, 4, 20]
列求和(相同长度):[0, 0, 0, 4, 12.1]
列求和:['', 0, '', '', 12.1, 6.0, 7.0]

10、获取时间字符串的月份数

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
from datetime import datetime

def get_months(start_month_str, end_month_str):
'''
# 获取时间字符串中的月份数
:param start_month_str: 开始字符串
:param end_month_str: 结束字符串
:return: 月份数
'''

end_month_date = datetime.strptime(end_month_str, '%Y-%m')
start_month_date = datetime.strptime(start_month_str, '%Y-%m')
end_year, end_month = end_month_date.year, end_month_date.month
start_year, start_month = start_month_date.year, start_month_date.month

return (end_year - start_year) *12 + (end_month - start_month) + 1


end_month_str = '2021-02'
start_month_str = '2020-07'
print(get_months(start_month_str, end_month_str))

输出:

8

11、字符串不足补零

1
2
3
4
5
6
7
8
9
print('hello world'.zfill(15)) # 补0
print('hello world'.rjust(15)) # 右对齐,补空格
print('hello world'.ljust(15)) # 左对齐,补空格

输出:

0000hello world
hello world
hello world

12、时间戳转字符串日期

1
2
3
4
5
6
7
8
import time
t1 = time.time()
print(t1)
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(t1)))

输出:
1621741567.082192
2021-05-23 11:46:07

使用函数:

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
# !/usr/bin/python
# -*- coding: utf-8 -*-

"""
@contact: 微信 1257309054
@file: 时间戳转日期.py
@time: 2022/6/27 17:16
@author: LDC
"""
import time
import datetime


# 正确10位长度的时间戳可精确到秒,11-14位长度则是包含了毫秒
def int_to_datetime(intValue):
if len(str(intValue)) == 10:
# 精确到秒
timeValue = time.localtime(intValue)
tempDate = time.strftime("%Y-%m-%d %H:%M:%S", timeValue)
datetimeValue = datetime.datetime.strptime(tempDate, "%Y-%m-%d %H:%M:%S")
elif 10 < len(str(intValue)) and len(str(intValue)) < 15:
# 精确到毫秒
k = len(str(intValue)) - 10
timetamp = datetime.datetime.fromtimestamp(intValue / (1 * 10 ** k))
datetimeValue = timetamp.strftime("%Y-%m-%d %H:%M:%S.%f")
else:
return -1
return datetimeValue


time1 = 1656321420
time2 = 1656321086560
print(int_to_datetime(time1))
print(int_to_datetime(time2))

'''
输出:
2022-06-27 17:17:00
2022-06-27 17:11:26.560000
'''

13、列表转字符串

1
2
3
4
5
a = [1,2,3]
print(','.join(map(str,a)))

输出:
`1,2,3`

14、pip国内镜像源

1
2
3
4
5
6
7
8
9
10
11
12
13
14
pip install 库名 -i https://pypi.tuna.tsinghua.edu.cn/simple


清华:-i https://pypi.tuna.tsinghua.edu.cn/simple

阿里云:-i http://mirrors.aliyun.com/pypi/simple/

中国科技大学 -i https://pypi.mirrors.ustc.edu.cn/simple/

华中理工大学:-i http://pypi.hustunique.com/

山东理工大学:-i http://pypi.sdutlinux.org/

豆瓣:-i http://pypi.douban.com/simple/

15、python把时间字符串转换成刚刚、1天前、3个月前、1年前

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
import datetime
import time


def date_interval(date_str):
'''
获取时间间隔
1分钟前,2分钟前,10分钟前,1小时前,2小时前,1天前,2天前,3天前,1个月前,3个月前,1年前,3年前
:param date_str: 时间字符串
:return: 字符串
'''
date_str = time.strptime(date_str, '%Y-%m-%d %H:%M:%S')
# 将时间元组转换为时间戳
t = time.mktime(date_str)

# 当前时间
seconds = time.time() - t

years = int(seconds // (60 * 60 * 24 * 365))
if years:
return '{}年前'.format(years)
months = int(seconds // (60 * 60 * 24 * 30))
if months:
return '{}月前'.format(months)
days = int(seconds // (60 * 60 * 24))
if days:
return '{}天前'.format(days)
hours = int(seconds // (60 * 60))
if hours:
return '{}小时前'.format(hours)
minutes = int(seconds // (60))
if minutes:
return '{}分钟前'.format(minutes)
return '刚刚'


if __name__ == '__main__':
date1 = '2019-07-10 15:27:51'
date2 = '2021-07-10 15:27:51'
date3 = '2021-08-10 15:27:51'
date4 = '2021-08-12 11:01:51'
date5 = datetime.datetime.now() + datetime.timedelta(seconds=-3)
date5 = date5.strftime('%Y-%m-%d %H:%M:%S')
print(date_interval(date1))
print(date_interval(date2))
print(date_interval(date3))
print(date_interval(date4))
print(date_interval(date5))

16、python获取电脑磁盘、CPU、内存使用情况

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
import psutil
# pip install psutil

# 获取本机磁盘使用率和剩余空间G信息
def get_disk_info():
# 循环磁盘分区
content = ""
for disk in psutil.disk_partitions():
# 读写方式 光盘 or 有效磁盘类型
if 'cdrom' in disk.opts or disk.fstype == '':
continue
disk_name_arr = disk.device.split(':')
disk_name = disk_name_arr[0]
disk_info = psutil.disk_usage(disk.device)
# 磁盘剩余空间,单位G
free_disk_size = disk_info.free//1024//1024//1024
# 当前磁盘使用率和剩余空间G信息
info = "{}盘使用率:{}%%, 剩余空间:{}G ".format(disk_name, str(disk_info.percent), free_disk_size)
# 拼接多个磁盘的信息
content = content + info
print(content)

# cpu信息
def get_cpu_info():
cpu_percent = psutil.cpu_percent(interval=1)
cpu_info = "CPU使用率:%i%%" % cpu_percent
print(cpu_info)

# 内存信息
def get_memory_info():
virtual_memory = psutil.virtual_memory()
used_memory = virtual_memory.used/1024/1024/1024
free_memory = virtual_memory.free/1024/1024/1024
memory_percent = virtual_memory.percent
memory_info = "内存使用:%0.2fG,使用率%0.1f%%,剩余内存:%0.2fG" % (used_memory, memory_percent, free_memory)
print(memory_info)

if __name__ == '__main__':
get_disk_info()
get_cpu_info()
get_memory_info()

17、max比较字典列表

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
'''
使用max函数比较字典列表对象
需求:找出用户组最大id的字典
'''
def com_id(f):
'''
比较用用户ids列表
:param f: 字典
:return: 返回最大的用户id
'''
return max(f['user_ids'])

friends_added = [
{'user_ids': [1, 2], 'create_at': '2020-01-01'},
{'user_ids': [3, 6], 'create_at': '2020-01-02'},
{'user_ids': [2, 1], 'create_at': '2020-02-02'},
{'user_ids': [4, 1], 'create_at': '2020-02-02'},
]
# max函数中使用key参数,指定自定义函数来比较
item = max(friends_added, key=com_id)
item_1 = max(friends_added, key=lambda f: max(f['user_ids'])) # com_id可以转成lambda函数
print(item)
print(item_1)


输出:

{'user_ids': [3, 6], 'create_at': '2020-01-02'}
{'user_ids': [3, 6], 'create_at': '2020-01-02'}

18、 列表取奇数下标值

1
2
3
4
5
6
list1=['a','b','c','d','e']
print('奇数下标值',list1[1::2])

输出:

奇数下标值 ['b', 'd']

19、列表取偶数下标值

1
2
3
list1=['a','b','c','d','e']
print('偶数下标值',list1[::2])
偶数下标值 ['a', 'c', 'e']

20、列表相同元素分类、分组

1
2
3
4
5
6
7
8
9
import itertools

data = [1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 1, 'a', 'a']
a =[list(group) for key, group in itertools.groupby(data)]
print(a)

输出:

[[1], [2, 2, 2, 2], [3, 3, 3], [4, 4, 4, 4], [1], ['a', 'a']]

21、numpy二维数组获取某一列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import numpy as np

a = [
[1, 2, 3, 4, 5, 6],
[7, 8, 9, 10, 11, 12],
[13.2, 14.8, 15.9, 16.10, 16.11, 17.12],
]

a_np = np.array(a) # 把二维列表转成numpy数组
print('第一行', a_np[0].tolist()) # 获取第一行
print('第一列', a_np[:, 0].tolist()) # 获取第一列

输出:

第一行 [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
第一列 [1.0, 7.0, 13.2]

__END__