分类: Python

  • python读取PDF文件中的指定页码的范围并的存储到指定的文件名

    # -*- coding: utf-8 -*-
    """
    Created on Mon Nov 27 21:36:12 2023
    
    @author: cnliu
    pip install pypdf2
    """
    from PyPDF2 import PdfWriter, PdfReader
    import os
    
    #pathToPDF = input('something like /home/pedro/Latin/ ... ')
    pathToPDF = "d:/书/"
    path2Extracts = 'd:/'
    # get the names of the files available to extract from
    files = os.listdir(pathToPDF)
    # show the files in a loop so you can choose 1
    # I haven't done that here
    # choose a PDF from a list of PDFs from  as bookname
    #bookTitle = bookname.replace('.pdf', '')
    bookname = "AHaSuanFa.pdf"
    # read the pdf
    pdf = PdfReader(pathToPDF + bookname)
    #pages = pdf.getNumPages() (deprecated)
    pages = len(pdf.pages)
    print('This pdf has ' + str(pages) + ' pages')
    print('What pages do you want to get?')
    startnum = input('what is the starting page number?  ')
    print('If your last page is page 76, enter 76 for the end number')
    endnum = input('what is the last page number?  ')
    start = int(startnum) - 1
    end = int(endnum)
    # only need to open pdfWriter 1 time
    pdf_writer = PdfWriter()
    for page in range(start, end):
            pdf_writer.add_page(pdf.pages[page])
    
    print('Enter the savename for this pdf, like CE3U8')
    savename = input('Enter the name to save this pdf under, like CE3U8 No need to add .pdf ... ')
    output_filename = savename + '.pdf'
    
    with open(path2Extracts + output_filename, 'wb') as out:
            pdf_writer.write(out)
    print(f'Created: {output_filename} and saved in', path2Extracts)
    print('All done!')
  • 本站二维码,python代码

    本网地址:http://cnliutz.ipyingshe.net
    import qrcode
    
    # 生成二维码
    data = "http://cnliutz.ipyingshe.net"
    img = qrcode.make(data)
    
    # 将二维码保存为图片
    with open('qrcode.png', 'wb') as f:
        img.save(f)
        img.open(f)
    import qrcode
    qr = qrcode.QRCode(version=1,box_size=10,border=5)
    data = input("Enter the url you want as a QR code: ")
    qr.add_data(data)
    qr.make(fit=True)
    img = qr.make_image(fill_color="black", back_color="white")
    img.save("qrcode.png")
  • Python 统计词频gui

    from tkinter import Tk, Label, Entry, Button, Canvas, Scrollbar
    from collections import defaultdict
    import matplotlib.pyplot as plt

    #统计词频

    def count_words(text):
    words = text.split()
    word_freq = defaultdict(int)
    for word in words:
    word_freq[word] += 1
    return word_freq

    #绘制词频图形

    def plot_word_freq(word_freq):
    plt.bar(word_freq.keys(), word_freq.values())
    plt.xlabel(‘Words’)
    plt.ylabel(‘Frequency’)
    plt.title(‘Word Frequency’)
    plt.show()

    #创建主窗口

    root = Tk()

    #创建标签和输入框

    label_text = Label(root, text=’请输入文本:’)
    entry_text = Entry(root)

    #创建按钮

    button_count = Button(root, text=’统计词频’, command=lambda: count_words(entry_text.get()))
    button_plot = Button(root, text=’绘制图形’, command=lambda: plot_word_freq(count_words(entry_text.get())))

    #创建画布和滚动条

    canvas = Canvas(root, width=800, height=600)
    scrollbar = Scrollbar(root, orient=’vertical’, command=canvas.yview)

    #在画布中添加文本标签、输入框、两个按钮
    label_text.pack()
    entry_text.pack()
    button_count.pack()
    button_plot.pack()

    #将画布和滚动条组合在一起

    canvas.configure(yscrollcommand=scrollbar.set)
    scrollbar.pack(side=’right’, fill=’y’)
    canvas.pack()

    #主循环

    root.mainloop()

  • python的基本语法

    Python 是一种解释型、高级和通用的编程语言。Python 的语法非常简单,以下是一些基本语法:
    1. 缩进:Python 使用缩进来标识代码块,而不是使用花括号 {}。
    2. 语句:Python 使用冒号 : 来表示语句的结束,而不是分号 ;。
    3. 标识符:Python 标识符由字母、数字和下划线组成,但不能以数字开头。标识符用于变量、函数和类的命名。
    4. 变量:Python 变量使用标识符来表示,可以在程序中存储和操作数据。
    5. 数据类型:Python 有多种数据类型,包括整数、浮点数、字符串、列表、元组和字典等。
    6. 运算符:Python 有多种运算符,包括数学运算符、比较运算符、逻辑运算符和赋值运算符等。
    7. 控制结构:Python 有多种控制结构,包括条件语句(if-else)、循环语句(for、while)和异常处理语句(try-except)等。
    8. 函数:Python 函数是一段可以重复使用的代码,用于执行特定的任务。函数接受参数并返回值。
    9. 模块:Python 模块是一个包含函数和变量的文件,可以被其他 Python 程序导入和使用。
    这些是 Python 编程语言的一些基本语法,如果您想深入学习 Python,可以参考官方文档或相关的教程和书籍。

  • python小知识

    myset ={1,2,3,4,5}
    myset.discard(3)
    print(myset)
    {1, 2, 4, 5}
    myset.discard(2)
    print(myset)
    {1, 4, 5}
    
  • Python数据分析实战-dataframe某列的值分成不同区间并计算频数

    2023-9-7 15:39

    实现功能

    将dataframe某列的值分成不同区间并计算每个区间的频数

    实现代码

    import pandas as pd
    
    # 创建dataframe
    data = {'Name':['Tom1', 'Jack1', 'Steve1', 'Ricky1', 'Tom2', 'Jack2', 'Steve2', 'Ricky2'],'Score':[78,60,59,42,88,34,69,142]}
    df = pd.DataFrame(data)
    print(df)
    
    # 定义区间和标签
    bins = [0, 60, 80, 90, float('inf')]
    labels = ['<=60', '60-80', '80-90', '90+']
    
    # 将 Score 列的值分入不同区间,并计算频数
    counts = pd.cut(df['Score'], bins=bins, labels=labels).value_counts().sort_index()
    
    print(counts)
  • 录屏python代码

    #Here is a simple Python code for screen recording using OpenCV library:
    # ```python
    # ---- pip install numpy pillow opencv-python pyautogui ----
    # cv2 from package of  opencv-python
    import cv2
    import numpy as np
    import pyautogui
    
    # Specify resolution
    resolution = (1920, 1080)
    #自动获取屏幕分辨率
    #screen_width, screen_height = pyautogui.size()
    #fourcc = cv2.VideoWriter_fourcc(*"XVID")
    #out = cv2.VideoWriter("screen_recording.avi", fourcc, 20.0, (screen_width, screen_height))
    
    # Specify video codec
    codec = cv2.VideoWriter_fourcc(*"XVID")
    
    # Specify name of Output file
    filename = "Recording.avi"
    
    fps = 60.0
    out = cv2.VideoWriter(filename, codec, fps, resolution)
    print("开始录制……文件名:" + filename)
    print("Ctrl+停止录制......")
    while True:
        img = pyautogui.screenshot()
        frame = np.array(img)
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        out.write(frame)
        if cv2.waitKey(1) == ord('q'):   #不知为什么,按q键无法退出运行!!!
            print("ctrl+c结束录屏")
            break
    
    out.release()
    cv2.destroyAllWindows()
  • 给图片添加文字(水印)方法python代码

    素材:名单f.xlsx
    序号 校区 姓名 电话 部门 职位
    351 上海普陀校区 曾志鹏 19307130192 咨询部 咨询
    352 杭州西湖校区 陈泽祥 19300180069 办公室 校长
    353 杭州西湖校区 戴子瑜 19300180001 教学部 教学经理
    354 杭州西湖校区 杜心怡 19300180142 咨询部 咨询经理
    355 北京中关村校区 葛明坤 19300180051 办公室 校长
    356 北京中关村校区 郭家成 19300180034 咨询 咨询顾问
    357 北京中关村校区 胡海辰 18307110233 教学部 教学经理
    358 石家庄校区 蒋超源 19307130014 办公室 校长
    359 石家庄校区 金雍奇 19300180057 咨询部 咨询经理
    360 石家庄校区 邝 麒 19300180102 教学部 讲师
    361 深圳宝安校区 李泽昊 19300180070 办公室 校长
    362 深圳宝安校区 厉 茗 19300180127 教学部 教学经理
    363 深圳宝安校区 吕文韬 19300180079 咨询部 咨询顾问
    364 成都天府校区 马 赫 19300180067 办公室 校长
    365 成都天府校区 宋明奇 19307110261 咨询部 咨询经理
    366 成都天府校区 吴家茂 19300180082 教学部 教学经理
    367 西安碑林校区 吴 强 19300180083 办公室 校长
    368 西安碑林校区 肖云洋 19307110356 咨询部 咨询顾问

    图片素材 src.jpg

    • 命令行安装运行需要的依赖包:pip install pillow openpyxl
    • python源代码:
    #运行环境:win11、python 3.11
    from PIL import Image, ImageDraw, ImageFont
    from openpyxl import load_workbook
    import random
    
    
    def task(username, userinfo):
        image = Image.open("./src.jpg")
        draw = ImageDraw.Draw(image)
        color = 'black'
        text = str(username)
        size = 34
        font = ImageFont.truetype(r"C:\Windows\Fonts\STXINWEI.ttf", size=size)
        text_width = draw.textlength(text, font)
        x = (image.width - text_width) / 2
        #x=125
        y = 120
        draw.text((x, y), text, font=font, fill=color)
    
        text = str(userinfo)
        size = 10
        font = ImageFont.truetype(r"C:\Windows\Fonts\STXINWEI.ttf", size=size)
        text_width = draw.textlength(text, font)
        x = (image.width - text_width) / 2
        #x =120
        y = 220
        draw.text((x, y), text, font=font, fill=color)
    
        image.save('img/' + str(userinfo) + '-' + str(username) + '.jpg')
        #image.save('img/' + str(random.randint(100000, 999999)) + '.jpg')
        #image.show()
    
    
    def import_data(file):
        workbook = load_workbook(file)
        sheet = workbook.active
        for row in sheet.iter_rows():
            row_data = [cell.value for cell in row]
            print(row_data[2])
            print(row_data[1])
            task(row_data[2], row_data[1])
    
    
    if __name__ == '__main__':
        import_data(r"E:\mysite\home\f.xlsx")
        print("success")
    
    
    
    效果图
  • 画图、写字(水印)draw multicolor rectangular horizontal and vertical gradients

    from PIL import Image, ImageDraw, ImageFont
    
    BLACK, DARKGRAY, GRAY = ((0,0,0), (63,63,63), (127,127,127))
    LIGHTGRAY, WHITE = ((191,191,191), (255,255,255))
    BLUE, GREEN, RED = ((0, 0, 255), (0, 255, 0), (255, 0, 0))
    
    
    class Point(object):
        def __init__(self, x, y):
            self.x, self.y = x, y
    
    class Rect(object):
        def __init__(self, x1, y1, x2, y2):
            minx, maxx = (x1,x2) if x1 < x2 else (x2,x1)
            miny, maxy = (y1,y2) if y1 < y2 else (y2,y1)
            self.min = Point(minx, miny)
            self.max = Point(maxx, maxy)
    
        width  = property(lambda self: self.max.x - self.min.x)
        height = property(lambda self: self.max.y - self.min.y)
    
    
    def gradient_color(minval, maxval, val, color_palette):
        """ Computes intermediate RGB color of a value in the range of minval
            to maxval (inclusive) based on a color_palette representing the range.
        """
        max_index = len(color_palette)-1
        delta = maxval - minval
        if delta == 0:
            delta = 1
        v = float(val-minval) / delta * max_index
        i1, i2 = int(v), min(int(v)+1, max_index)
        (r1, g1, b1), (r2, g2, b2) = color_palette[i1], color_palette[i2]
        f = v - i1
        return int(r1 + f*(r2-r1)), int(g1 + f*(g2-g1)), int(b1 + f*(b2-b1))
    
    def horz_gradient(draw, rect, color_func, color_palette):
        minval, maxval = 1, len(color_palette)
        delta = maxval - minval
        width = float(rect.width)  # Cache.
        for x in range(rect.min.x, rect.max.x+1):
            f = (x - rect.min.x) / width
            val = minval + f * delta
            color = color_func(minval, maxval, val, color_palette)
            draw.line([(x, rect.min.y), (x, rect.max.y)], fill=color)
    
    def vert_gradient(draw, rect, color_func, color_palette):
        minval, maxval = 1, len(color_palette)
        delta = maxval - minval
        height = float(rect.height)  # Cache.
        for y in range(rect.min.y, rect.max.y+1):
            f = (y - rect.min.y) / height
            val = minval + f * delta
            color = color_func(minval, maxval, val, color_palette)
            draw.line([(rect.min.x, y), (rect.max.x, y)], fill=color)
    
    
    if __name__ == '__main__':
        # Draw a three color vertical gradient.
        color_palette = [BLUE, GREEN, RED]
        image_w = 300
        image_h = 200
        region = Rect(0, 0, image_w, image_h)
        imgx, imgy = region.max.x + 1, region.max.y + 1
        image = Image.new("RGB", (imgx, imgy), WHITE)
        draw = ImageDraw.Draw(image)
        vert_gradient(draw, region, gradient_color, color_palette)
        # image.text((40, 80),"No Artwork",(255,255,255))
        font = ImageFont.truetype(r'C:\Users\System-Pc\Desktop\arial.ttf', 40)
        # font = ImageFont.load_default()
        #font = ImageFont.truetype("Ubuntu-R.ttf", int(float(image_w) / 6))
        draw.text((int(image_w / 12), int(image_h / 2.5)), "No Artwork", \
                  fill=(0, 0, 0), font=font)
        image.show()
        # image.save("vert_gradient.png", "PNG")
        # print('image saved')