Python奇技淫巧

1、简单的代码示例

import os

# 1、快速实现字频统计
def func1():
    from collections import Counter

    words1 = '''我明白你的意思,你的意思就是想意思意思,但是你不明白我的意思,我的意思是你不用意思意思,你懂我的意si吗'''
    word_count = Counter(words1)
    # 输出出现次数最多的两个元素
    top_three = word_count.most_common(2)
    print("1:",top_three)
    list1 = list(words1)
    print("1:",max(set(list1), key=list1.count))

# 2、汉字转拼音
def func2():
    import pypinyin

    words2 = "安能使我摧眉折腰事权贵"
    zimu = pypinyin.pinyin(words2)
    print("2:",zimu)

# 3、查看某个文件夹是否含有python格式的文件(或其他格式)
def func3():
    files = os.listdir("D:\Django\day20210408")
    if any(name.endswith('.py') for name in files):
        print("3:有")

    for file in files:
        if file.endswith('.py'):
            print("3:真有")

# 4、快速打印字符串
def func4():
    rows = ["我","爱","北京","天安门"]
    print("4:",*rows)

# 5、计算两个日期的间隔天数
def func5():
    from datetime import date
    d1 = date(2021, 4, 19)
    d2 = date(2021, 12, 31)
    print("5:", abs(d2 - d1).days)

# 6、将值追加到字典某个键下的列表中
def func6():
    d = {}
    l = []
    d.setdefault(2, l)
    print("6:",d)
    d.setdefault(2, l).append(23)
    print("6:",d)

# 7、查看某个变量占用内存的大小
def func7():
    import sys
    x = 11
    print("7:",sys.getsizeof(x))

# 8、随机返回几个字母组成的单词
def func8():
    import random, string
    randword = lambda n: "".join([random.choice(string.ascii_letters) for i in range(n)])
    # print(randword)

# 9、打印进度条
def func9_1():
    import time
    import sys
    for progress in range(100):
        time.sleep(0.1)
        sys.stdout.write("9: Download progress: %d%%   \r" %(progress))
        sys.stdout.flush()

def func9_2():
    from progress.bar import Bar

    bar = Bar('Processing', max=20)
    for i in range(20):
        bar.next()
    bar.finish()

def func9_3():
    from tqdm import tqdm
    for i in tqdm(range(int(9e6))):
        pass

# 10、快速反转字符串
def func10():
    python = 'Python is the best language In The World'
    print("10:",python[::-1])

# 11、找出两个列表中不一样的元素
def func11():
    list_1 = ['Lishang', 'Sunkaixin', 'Zhaoxiaomeng', 'Liwenwen']
    list_2 = ['Lishang', 'Sunkaixin', 'Zhaoxiaomeng', 'Xiangmei', 'Wangyiju']

    set_1 = set(list_1)
    set_2 = set(list_2)
    print("11 交集:", set_1&set_2)
    print("11 并集:", set_1|set_2)
    print("11 差集:", set_2-set_1)
    print("11 补集:", set_1 ^ set_2)
    print("11: 两个列表中不一样的元素为:", list(set_1.symmetric_difference(set_2)))

# 12、删除列中的重复项, 并对数字进行排序
def func12():
    listnumber = ['56', '11', '34', '23', '45', '67', '89', '92', '78', '34', '67']
    # set函数去重
    c = list(set(listnumber))
    # map函数将字符串转换成数字, 在Python2.x中直接用map, Python3.x中map是一个对象
    d = list(map(int, c))
    # sorted函数对数字排序
    e = sorted(d, reverse=False)
    print("12:", e)

# 13、两个列表转换成字典
def func13():
    items = [23, 45, 67]
    values = ["Python", "Go", "C++"]
    new_dictionary = dict(zip(items,values))
    print("13:",new_dictionary)

# 14、移除字符串中的标点
def func14():
    puncttions = '''!()-[]{};'"\,<>./?@#$%^&*_~,。?!'''
    my_str = "你好,,小朋友!!~我的名字是:隔-壁-老-王。。"

    # 移除标点
    no_punc = ""
    for i in my_str:
        if i not in puncttions:
            no_punc = no_punc + i

    print("14:",no_punc)

# 15、创建一个文件
def func15():
    MESSAGE = "该文件已存在"
    TESTDIR = 'testdir'
    try:
        home = os.path.expanduser("E:\SQL")

        if not os.path.exists(os.path.join(home, TESTDIR)):
            os.makedirs(os.path.join(home, TESTDIR))
        else:
            print("%s路径下" %home,MESSAGE )
    except Exception as e:
        print("333",e)

if __name__ == '__main__':
    func9_3()

2、数字大小排序

# -*- coding:utf-8 -*-
# Author: li Shang

# number = input("Please enter 3 numbers: ")
# number = list(number)
number = [90, 100, 99]

a = int(number[0])
b = int(number[1])
c = int(number[2])

new_l = []

if a > b and a > c:
    new_l.append(a)
    if b > c:
        new_l.append(b)
        new_l.append(c)
    else:
        new_l.append(c)
        new_l.append(b)
    print(new_l)

elif b > a and b > c:
    new_l.append(b)
    if a > c:
        new_l.append(a)
        new_l.append(c)
    else:
        new_l.append(c)
        new_l.append(a)
    print(new_l)

elif c > a and c > b:
    new_l.append(c)
    if a > b:
        new_l.append(a)
        new_l.append(b)
    else:
        new_l.append(b)
        new_l.append(a)
    print(new_l)

else:
    print("Game Over")

3、连接影城

#-*- coding:utf-8 -*-
# Author: li Shang

import pymysql

def num(cid):
    '''连接10.10.0.90mysql'''
    global data_ip,n,bj_vpn
    conn1 = pymysql.connect(host='10.10.0.90', port=3306, user='write', passwd='yhz#write#dc', db='cinema')
    # 1、获取游标
    cursor1 = conn1.cursor()
    # 2、调用查询sql
    effect_row = cursor1.execute("select * from cinema_info where cinema_num = %s",(cid))
    # 3、使用fethall来获取游标中的结果集
    data = list(cursor1.fetchall())
    # print(data)                          #返回结果
    b= data[0]
    name, bj_vpn, sh_vpn, data_ip= b[6], b[4], b[5], b[15]
    print("影城名字为: \033[1;30;46m%s\033[0m" %name)
    print("bj_vpn为: \033[1;30;44m%s\033[0m,sh_vpn为: \033[1;30;45m%s\033[0m" %(bj_vpn,sh_vpn))
    # print("sh_vpn为: \033[1;30;45m%s\033[0m" %sh_vpn)
    print("所在的数据中心ip为: \033[1;30;43m%s\033[0m" %data_ip)
    n = "C%s" %cid
    conn1.commit()    # 提交,不然无法保存新建或者修改的数据
    cursor1.close()   # 关闭游标
    conn1.close()     # 关闭连接

def func1():
    '''连接数据中心数据库'''
    conn = pymysql.connect(host=data_ip, port=3306, user='queryuser', passwd='123456', db=n)
    cursor = conn.cursor()
    effect_row1 = cursor.execute("SELECT * FROM cinema_sell_log ORDER BY cinema_sell_time DESC limit 1")
    data = list(list(cursor.fetchall())[0])
    x, y, z = data[20], data[9], data[19]
    print("数据中心记录的最后一张票的售卖时间为:\033[1;30;41m%s\033[0m,电影为: \033[1;30;46m%s\033[0m,渠道或售票人为: \033[1;30;46m%s\033[0m" %(x,y,z))
    conn.commit()   # 提交,不然无法保存新建或者修改的数据
    cursor.close()  # 关闭游标
    conn.close()    # 关闭连接

def func2():
    k='cine'
    '''连接该影城数据库'''
    conn = pymysql.connect(host=bj_vpn, port=3306, user='yunwei', passwd='UiBxKwCt', db=k)
    cursor = conn.cursor()
    effect_row2 = cursor.execute("SELECT * FROM cinema_sell_log ORDER BY cinema_sell_time DESC limit 1")
    data=cursor.fetchall()
    data = list(list(data)[0])
    x_1, y_1, z_1 = data[20], data[9], data[19]
    print("单机last ticket's sell time: \033[1;30;41m%s\033[0m, name:%s, from:%s" %(x_1,y_1,z_1))

    conn.commit()  # 提交,不然无法保存新建或者修改的数据
    cursor.close()  # 关闭游标
    conn.close()  # 关闭连接

# pyinstaller.exe -w -F -i ww.ico D:\python3.9\项目1\Lishang_pro\爱心.py
# python国内镜像
# pip install --index https://pypi.mirrors.ustc.edu.cn/simple gevent == 1.4.0
# pip install -i https://pypi.douban.com/simple gevent == 1.4.0
if __name__ == '__main__':
    data_ip = 0
    n = 0
    a = input(">>>:").strip()
    print("你要查询的影院编码为:\033[1;30;42m%s\033[0m" %a )
    num(a)
    func1()
    func2()
posted @ 2022-02-18 17:44  中國颜值的半壁江山  阅读(53)  评论(0)    收藏  举报