python实用小方法

一、创建随机字母

import random

# 创建随机字母
def make_code(n):
    res = ''
    for i in range(n):
        num = str(random.randint(1, 9))  # 随机选取1到9的一个整数
        letter = chr(random.randint(65, 90))  # 随机选大写英文的一个字母
        group = random.choice([num, letter])  # 随机选取整数还是大写字母
        res += group  # 循环次数加到空字符串中
    return res
print(make_code(4))

二、正则匹配出需要的文件

# 正则匹配出需要的文件
import glob

path = r"D:\PycharmProjects\maple\face"
for name in glob.glob('{}\*[0-9].*'.format(path)):
    print(name)
# 结果
# D:\PycharmProjects\maple\face\Myface1.jpg
# D:\PycharmProjects\maple\face\Myface2.jpg
# D:\PycharmProjects\maple\face\Myface3.jpg
# D:\PycharmProjects\maple\face\Myface4.jpg
# D:\PycharmProjects\maple\face\Myface5.jpg

三、判断元素是否为数字

import numpy as np
# 判断元素是否为数字
def is_number(s):
    try:
        if np.isnan(s) or s == False or s == True:
            return False
    except Exception:
        pass
    try:
        # 判断是否为浮点数
        float(s)
        return True
    except Exception:
        pass
    try:
        import unicodedata  # 处理ASCii码的包
        # 把一个表示数字的字符串转换为浮点数返回的函数
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass
    return False


numbers = [12, "43", "地方", None, np.nan, 88.99, False, True]
print([is_number(i) for i in numbers])
# 结果
# [True, True, False, False, False, True, False, False]

五、格式化

# 格式化10进制
print(format(10,"b"))
# 格式化8进制
print(format(10,"o"))
# 格式化16进制
print(format(10,"x"))

六、精确处理数字

# 精确处理数字
a=1.1
b=3.2
print(a+b)

from decimal import Decimal
a=Decimal('1.1')
b=Decimal('3.2')
print(a+b)

七、正则匹配

# 正则匹配
import re
# 邮箱
res1='email1:[email protected] email2:[email protected] eamil3:[email protected]'
res=re.findall('\d+@\w+\.\w+',res1)
print(res)
# 数字
res2="1-12*(60+(-40.35/5)-(-4*3))"
res=re.findall('(\d+\.\d+|\d+)',res2)
print(res)

八、flask-web

from aiohttp import web
async def index(request):
    return web.Response(text='Hello World')

async def api(request):
    data = await request.json()
    question = data['question']
    return web.json_response({"state":question})

app = web.Application()
app.add_routes([web.get('/', index),
                web.post('/api', api)])

if __name__ == '__main__':
    web.run_app(app, host='127.0.0.1', port=5000)

猜你喜欢

转载自www.cnblogs.com/angelyan/p/12116481.html