分类: Python

  • python字符串函数

    course = 'Python  for beginner'
    print(course)
    print(course.upper())
    print(course.lower())
    print(course.find('f'))
    print(course.find('beginner'))
    print(course.replace('beginner','start'))
    print(course)
    print('Python' in course)
    print(len(course))
    print(course.title())
    
  • gui笔记本和任务列表Python代码

    首先,我们需要使用Python的Tkinter库来创建GUI界面。以下是一个简单的记事本和任务列表程序:
    
    ```python
    import tkinter as tk
    from tkinter import filedialog, messagebox
    
    class NotepadApp:
        def __init__(self, root):
            self.root = root
            self.root.title("记事本")
            self.root.geometry("800x600")
    
            self.create_widgets()
    
        def create_widgets(self):
            self.text = tk.Text(self.root, wrap=tk.WORD)
            self.text.pack(expand=True, fill=tk.BOTH)
    
            self.menu = tk.Menu(self.root)
            self.root.config(menu=self.menu)
    
            self.file_menu = tk.Menu(self.menu)
            self.menu.add_cascade(label="文件", menu=self.file_menu)
            self.file_menu.add_command(label="新建", command=self.new_file)
            self.file_menu.add_command(label="打开", command=self.open_file)
            self.file_menu.add_command(label="保存", command=self.save_file)
            self.file_menu.add_separator()
            self.file_menu.add_command(label="退出", command=self.root.quit)
    
            self.label = tk.Label(self.root, text="任务列表")
            self.label.pack(side=tk.TOP, fill=tk.X)
    
            self.task_list = tk.Listbox(self.root,fg="blue")
            #self.task_list = tk.Listbox(self.root, bg='light grey', fg='blue', bd=1, height=10, width=20, selectmode='MULTIPLE',state="normal",yscrollcommand='yes')
            self.task_list.pack(side=tk.TOP, fill=tk.BOTH)
    
    
            self.del_list_button = tk.Button(self.root, text="删除任务", command=self.del_list)
            self.add_task_button = tk.Button(self.root, text="添加任务", command=self.add_task)
            self.del_list_button.pack(side=tk.BOTTOM, fill=tk.Y)
            self.add_task_button.pack(side=tk.BOTTOM, fill=tk.Y)
    
        def new_file(self):
            self.text.delete(1.0, tk.END)
    
        def open_file(self):
            file_path = filedialog.askopenfilename()
            if file_path:
                with open(file_path, "r") as file:
                    content = file.read()
                self.text.delete(1.0, tk.END)
                self.text.insert(tk.INSERT, content)
    
        def save_file(self):
            file_path = filedialog.asksaveasfilename()
            if file_path:
                with open(file_path, "w") as file:
                    content = self.text.get(1.0, tk.END)
                    file.write(content)
    
        def add_task(self):
            task = self.text.get(1.0, tk.END)   #让上部文本,添加到下面的列表
            #task = "I am teacher!"
            if task:
                self.task_list.insert(tk.END, task)
                #self.task_list.delete(0, tk.END)     #清除下面列表内容
        def del_list(self):
            self.task_list.delete(0, tk.END)
            self.task_list.insert(tk.END, "--cnliutz--")
    
    
    if __name__ == "__main__":
        root = tk.Tk()
        app = NotepadApp(root)
        root.mainloop()
    ```
    
    这个程序实现了一个简单的记事本功能,包括新建、打开和保存文件。同时,还有一个任务列表框和一个添加任务按钮。你可以根据需要进一步完善这个程序。
    
    (内容由讯飞星火AI生成)
  • python代码操作sqlite3数据库CRUD

    #python sqlite3数据库创建、增、删、查、改
    import sqlite3
    
    #生成一个数据库连接对象conn
    conn = sqlite3.connect("test.db") # 如果文件不存在,会自动创建
    #您可以通过连接对象创建一个游标对象,用于执行 SQL 语句,例如:
    
    cursor = conn.cursor()
    cursor.execute("create table if not exists user (id integer primary key, name text, age integer)") # 创建一个 user 表
    cursor.execute("insert into user (id, name, age) values (1, 'Alice', 20)")  # 插入一条记录
    for i in range(2, 10):
        cursor.execute("insert into user (name, age) values ('cnliutz', {})".format(60+i))
        # Replace 'Unknown' with the actual name
        data = ('John Doe'+str(i), 25+i)
        cursor.execute("insert into user (name, age) values ( ?, ?)", data)
    
    conn.commit() # 提交事务
    
    #您可以使用游标对象的 fetchone(), fetchmany() 或 fetchall() 方法来获取查询结果集中的数据,例如:
    
    cursor.execute("select * from user where age > 18") # 查询年龄大于 18 的用户
    users = cursor.fetchall() # 获取所有符合条件的用户
    for user in users:
        print(user) # 打印每个用户的信息
    
    #您可以使用游标对象的 execute() 或 executemany() 方法来更新或删除数据,例如:
    
    cursor.execute("update user set age = 21 where id = 1") # 更新 id 为 1 的用户的年龄为 21
    cursor.executemany("delete from user where name = ?", [("Alice",), ("Bob",)]) # 删除名字为 Alice 或 Bob 的用户
    conn.commit() # 提交事务
    
    #最后,您需要关闭游标和连接对象,以释放资源,例如:
    
    cursor.close()
    conn.close()

    注意插入数据时的灵活性

  • python录屏

    
    #录制屏幕30秒
    import pyautogui
    import cv2
    import numpy as np
    
    # Set the recording resolution and framerate
    resolution = (1920,1080)
    fps = 30
    
    # Start recording the screen
    #screen_capture = pyautogui.screenshot()
    # Convert the screenshot to a numpy array
    #screen_capture = np.array(screen_capture)
    # Create a VideoWriter object to save the video
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter('output.mp4', fourcc, fps, resolution)
    
    # Record the screen for 10 seconds
    for i in range(10 * fps):
       # Capture a screenshot
       screen_capture = pyautogui.screenshot()
       # Convert the screenshot to a numpy array
       screen_capture = np.array(screen_capture)
       # Write the numpy array to the video file
       out.write(screen_capture)
    
    # Release the VideoWriter object and close the video file
    out.release()
    cv2.destroyAllWindows()
    print("saved to output.mp4....")
  • python画花瓣

    # -*- coding: utf-8 -*-
    """
    Spyder Editor
    
    This is a flower script file.
    """
    
    import turtle as t
    
    t.speed(11)
    t.pensize(5)
    color = ["blue","red","yellow","brown","green"]
    R = 210
    t.color("black","pink")
    t.begin_fill()
    for j  in range(5):
        R  -= 20
        t.pencolor(color[j])
        for i in range(10):
                t.circle(R,90)
                t.left(90)
                t.circle(R,90)
                t.left(90)
                t.left(36)
    t.end_fill()
    t.done()
    
  • 高效的单行python脚本

    https://m.toutiao.com/is/i8JUWns6/
    10 个高效的单行 Python 脚本 – 今日头条

    # -*- coding: utf-8 -*-
    """
    Created on Wed Dec  6 13:42:00 2023
    
    @author: czliu
    """
    
    # 1. 平方列表推导
    # 使用列表推导法计算从 1 到 10 的数字平方
    
    squares = [x**2 for x in range(1, 11)]
    print(squares)
    # 2.求偶数
    # 可以使用列表推导式从列表中筛选偶数。还可以出于其他目的修改此代码。
    
    even_numbers = [x for x in range(1, 11) if x % 2 == 0]
    print(even_numbers)
    # 3. 交换变量
    # 通常,交换变量的值需要另一个变量和一堆行,但在 Python 中,可以在一行中执行此操作。
    a=23
    b=25
    a, b = b, a
    print(a,b)
    # 4.反转字符串
    # 有时需要反转字符串。可以通过使用另一个变量和一个for循环来做到这一点,这有点复杂。可以用切片来代替
    
    reversed_string = "Hello, World!"[::-1]
    print(reversed_string)
    # 5. 计算字符串列表中的单词出现次数
    # 有一个句子列表,需要检查有多少个 X 单词。
    sentences = ["]this"," world ","is","not"," that","world","all world is ","word"," in ","sentence!"]
    # for sentence in sentences:
    #     print(sentence)
    word_count = sum(1 for sentence in sentences if "world" in sentence)
    print(word_count)
    # 6. 用于排序的 Lambda 函数
    # 可以使用 Lamba 函数根据特定键对字典列表进行排序。sortin
    #worlds =  {'a': 1, 'b': 2, 'b': '3'}
    dict_list = {'a':28,'b':25,'c':76}
    # sorted_list = sorted(dict_list, key=lambda x: x['key'])
    sorted_list = sorted(dict_list.items(), key=lambda x: x[1])
    print(type(sorted_list))
    print(sorted_list)
    # 7. 在列表中查找唯一元素
    # 可以使用 set 从列表中获取唯一元素
    
    original_list = [12,34,12,45,'t','w','w']
    unique_elements = list(set(original_list))
    # 8. 检查回文
    # 回文是一个单词、短语或句子,其向后读法与向前读法相同。通过反转来检查字符串是否为回文。
    string = 'abcdcba'
    is_palindrome = string == string[::-1]
    print(is_palindrome)
    
    # 9. 在 Sentece 中颠倒单词
    # 使用列表推导和功能颠倒句子中单词的顺序。join
    sentence = "this world is not that world,all world is word in sentence!"
    reversed_sentence = ' '.join(sentence.split()[::-1])
    print(reversed_sentence)
    # 10. 检查字符串是否为回文(不区分大小写):
    # 检查字符串是否为回文,忽略大小写,通过反转它和函数。
    my_string = 'AbcdcBa'
    is_palindrome = my_string.lower() == my_string[::-1].lower()
    print(is_palindrome)
    
  • 录屏python代码来自chatgpt3.5

    import pyautogui
    import imageio
    
    # Set the duration of the recording in seconds
    duration = 10
    
    # Specify the frames per second (FPS) for the video
    fps = 10
    
    # Specify the output file name
    output_file = 'screen_recording.mp4'
    
    # Get the screen resolution
    screen_width, screen_height = pyautogui.size()
    
    # Create a writer object to save the video
    writer = imageio.get_writer(output_file, fps=fps)
    
    try:
        for _ in range(int(fps * duration)):
            # Capture a screenshot
            screenshot = pyautogui.screenshot()
    
            # Convert the screenshot to a NumPy array
            frame = imageio.core.util.Array(screenshot)
    
            # Add the frame to the video
            writer.append_data(frame)
    finally:
        # Close the writer to save the video
        writer.close()
    
    print(f"Screen recording saved to {output_file}")
    
  • pyautogui库的使用-包括录屏功能

    #__decode__ =  "utf-8"
    # 掌握自动化:Python PyAutoGUI详解
    # 原创2023-11-29 10:00·涛哥聊Python
    
    # 介绍
    # Python的pyautogui库是一种用于自动化任务的强大工具,它可以模拟鼠标和键盘操作,执行各种GUI任务。无论是进行屏幕截图、自动填写表单、自动化测试还是进行GUI操作,pyautogui都可以派上用场。
    
    # 安装
    # 首先,确保已经安装了pyautogui库。使用pip来安装它:
    
    # pip install pyautogui
    # 基本操作
    # 导入pyautogui库
    # 要使用pyautogui,首先需要导入该库:
    
    import pyautogui
    # 获取屏幕尺寸
    # 可以使用以下命令获取屏幕的宽度和高度:
    
    screen_width, screen_height = pyautogui.size()
    print(f"屏幕宽度: {screen_width}, 屏幕高度: {screen_height}")
    # 鼠标操作
    # 获取鼠标当前位置
    # 要获取鼠标当前的位置,可以使用以下命令:
    
    x, y = pyautogui.position()
    print(f"鼠标当前位置: x={x}, y={y}")
    # 移动鼠标
    # 使用pyautogui.moveTo()函数,您可以将鼠标移动到指定的坐标位置:
    
    pyautogui.moveTo(100, 100, duration=1)  # 将鼠标移动到(100, 100)的位置,持续1秒
    # 鼠标点击
    # 使用pyautogui.click()函数,您可以模拟鼠标点击操作:
    
    pyautogui.click(200, 200)  # 在(200, 200)位置单击鼠标左键
    # 鼠标滚轮滚动
    # 要模拟鼠标滚轮滚动,可以使用pyautogui.scroll()函数:
    
    pyautogui.scroll(10)  # 向上滚动10个单位
    pyautogui.scroll(-10)  # 向下滚动10个单位
    # 键盘操作
    # 键盘输入
    # 使用pyautogui.typewrite()函数,可以模拟键盘输入:
    
    pyautogui.typewrite("Hello, World!")  # 输入文本
    # 模拟快捷键
    # 要模拟快捷键,可以使用pyautogui.hotkey()函数:
    
    pyautogui.hotkey("ctrl", "c")  # 模拟Ctrl+C
    # 按下和释放键盘按键
    # 使用pyautogui.keyDown()和pyautogui.keyUp()函数,可以按下和释放键盘按键:
    
    pyautogui.keyDown("shift")  # 按下Shift键
    pyautogui.keyUp("shift")  # 释放Shift键
    # 等待和延迟
    # 延迟执行
    # 使用pyautogui.sleep()函数,可以添加延迟以等待操作完成:
    
    pyautogui.sleep(2)  # 等待2秒
    # 等待特定的图像出现
    # pyautogui.locateOnScreen()函数可以用于等待并定位屏幕上的特定图像,以便后续操作:
    
    location = pyautogui.locateOnScreen("image.png")
    if location is not None:
        x, y, width, height = location
        pyautogui.click(x + width / 2, y + height / 2)
    # 屏幕交互
    # 识别屏幕上的颜色
    # 使用pyautogui.pixel()函数,可以获取屏幕上指定位置的像素颜色:
    
    color = pyautogui.pixel(300, 300)
    print(f"颜色值:{color}")
    # 查找图像位置
    # pyautogui.locateCenterOnScreen()函数可以用于查找屏幕上特定图像的中心位置:
    
    position = pyautogui.locateCenterOnScreen("image.png")
    if position is not None:
        x, y = position
        pyautogui.click(x, y)
    # 屏幕录制
    # pyautogui还可以用于屏幕录制,以便记录和重放屏幕操作。pyautogui可以与其他库一起使用,如cv2(OpenCV)来执行屏幕录制和回放。
    
    # 以下是如何使用pyautogui进行屏幕录制的简单示例:
    
    import pyautogui
    import cv2
    import numpy as np
    
    # 设置屏幕录制的区域(示例为整个屏幕)
    screen_width, screen_height = pyautogui.size()
    fourcc = cv2.VideoWriter_fourcc(*"XVID")
    out = cv2.VideoWriter("screen_recording.avi", fourcc, 20.0, (screen_width, screen_height))
    
    # 开始录制
    while True:
        # 获取屏幕截图
        screenshot = pyautogui.screenshot()
        frame = np.array(screenshot)
    
        # 将截图添加到录制中
        out.write(frame)
    
        # 显示录制的画面(可选)
        cv2.imshow("Screen Recording", frame)
    
        # 按下q键停止录制
        if cv2.waitKey(1) == ord("q"):
            break
    
    # 停止录制并释放资源
    out.release()
    cv2.destroyAllWindows()
    
    # 上述代码创建了一个屏幕录制的视频文件(screen_recording.avi),它不仅捕获屏幕上的图像,还保存录制的视频。可以通过按下 "q" 键来停止录制。
    
    # 示例应用
    # 示例 1: 模拟鼠标点击和键盘输入
    import pyautogui
    
    # 模拟鼠标点击
    pyautogui.click(100, 100)  # 在屏幕上坐标(100, 100)的位置单击
    
    # 模拟键盘输入
    pyautogui.write('Hello, World!')  # 在焦点处输入文本
    # 示例 2: 屏幕截图
    import pyautogui
    
    # 截取整个屏幕
    screenshot = pyautogui.screenshot()
    screenshot.save('screenshot.png')
    # 示例 3: 自动化数据输入
    import pyautogui
    
    # 定义数据
    data = "This is some data"
    
    # 单击文本框
    pyautogui.click(200, 200)
    
    # 输入数据
    pyautogui.write(data)
    # ------------
    # 示例 4: 自动化文件操作
    import pyautogui
    
    # 打开文件资源管理器
    pyautogui.hotkey('win', 'e')
    
    # 等待文件资源管理器打开
    pyautogui.sleep(1)
    
    # 复制文件
    pyautogui.hotkey('ctrl', 'c')
    
    # 切换到另一个文件夹
    pyautogui.hotkey('ctrl', 'v')
    
    
    # 示例 5: 自动化网页操作
    import pyautogui
    import webbrowser
    import time
    
    # 打开浏览器
    webbrowser.open('https://www.example.com')
    
    # 等待页面加载
    time.sleep(5)
    
    # 模拟滚动鼠标滚轮
    pyautogui.scroll(3)  # 向上滚动3次
    # 总结
    # Python的pyautogui库提供了强大的自动化工具,可用于模拟鼠标和键盘操作,
    # 执行各种GUI任务。无论是自动化日常任务还是进行游戏作弊,
    # pyautogui都能满足您的需求。
  • python打印99乘法表

    #以下是一个用 Python 打印九九乘法表的示例程序:
    
    #python
    
    for i in range(1, 10):
        for j in range(1, i+1):
            print(f"{j}x{i}={i*j}",end="\t")
        print('\n')
    
    
    #使用Python的reduce函数(需要安装functools库)
    
    #!/usr/bin/python
    #coding:utf-8
    #author:菜就多练呀
    from functools import reduce
    def add(x, y):
        return x + y
    total = reduce(add, range(1, 101))
    print(total)
        
  • 6种方式:用python求出1-100的和

    #方法一
    sum2=0
    for i in range(1,101):
        sum2+=i
    print("___sum1___")
    print(sum2)
    
    #方法二
    def fsum(n):
        s=0
        for i in range(1,n+1):
           s+=i
        print(s)
    print("----sum2----")
    fsum(100)
    
    
    #方法三while循环实现
    def fsum1(n):
        i=0 #初始化变量
        s=0
        while i < n+1: #条件判断
            s +=i #循环体
            i +=1 #改变变量
        print(s)
    print("----sum3----")
    fsum1(100)
    
    #方法四递归的思路
    def fsum2(n):
        if n==1:
            return 1
        else:
            return n+fsum2(n-1)
    print("----sum4----")
    print(fsum2(100))
    
    #方法五一句代码搞定
    print("----sum5----")
    print(sum(list(range(1,101))))
    
    #方法六:使用Python的reduce函数(需要安装functools库)
    
    #!/usr/bin/python
    #coding:utf-8
    #author:菜就多练呀
    from functools import reduce
    def add(x, y):
        return x + y
    total = reduce(add, range(1, 101))
    print("----Sum6 Total----")
    print(total)