标签: code

  • 【网站】为WordPress添加APlayer播放器

    引入方式类似prism,由于使用概率较大,因此在主题模板函数中进行全局引入:

    // Function to add APlayer.mini.css and APlayer.mini.js to the site
    function add_APlayer() {
        
        wp_register_style(
            'APlayerCSS', // handle name for the style 
            get_stylesheet_directory_uri() . '/APlayer.css' // location of the file
        );
    
        wp_register_script(
            'APlayerJS', // handle name for the script 
            get_stylesheet_directory_uri() . '/APlayer.js' // location of the file
        );
    
        // Enqueue the registered style and script files
        wp_enqueue_style('APlayerCSS');
        wp_enqueue_script('APlayerJS');
    }
    add_action('wp_enqueue_scripts', 'add_APlayer');

    然后采用 APlayer官方文档 中描述的方式引入:

    <div id="aplayer">
    </div>
    <script>
    const ap = new APlayer({
        container: document.getElementById('aplayer'),
        audio: [{
            name: '',
            artist: '',
            url: '',
            cover: ''
        }]
    });
    </script>

  • 【Python】对本地网页进行元素提取并输出Excel

    一些网页通过加载Js来保护页面元素,当我们突破Js得到本地页面时,可以使用BS4库对页面进行分析,提取对应的元素来综合有价值的内容。

    示例代码:

    import requests
    from bs4 import BeautifulSoup
    import pandas as pd
    
    # 发送请求并获取网页内容
    url = 'your_local_or_online_page_url'
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # 定义一个空的列表来存储提取的数据
    data = []
    
    # 遍历页面中的项目列表,假设项目数据都在某个父元素中
    projects = soup.find_all('tr', class_='project-id')  # 根据实际情况修改选择器
    
    # 提取每个项目的各项数据
    for project in projects:
        # 获取项目ID
        project_id = project.find('td', class_='project-id-class').get_text(strip=True)  # 修改为实际选择器
        
        # 将提取的数据添加到列表中
        data.append([project_id]) # 按实际修改
    
    # 创建 DataFrame 并保存为 Excel
    df = pd.DataFrame(data, columns=['ID']) # 按实际修改
    df.to_excel('projects_data.xlsx', index=False)
    
    print("Data has been successfully extracted and saved to 'projects_data.xlsx'.")

    主要用到了BS4库。

    示意代码:

    from bs4 import BeautifulSoup
    
    # 假设有一个HTML文档
    html_doc = """
    <html>
      <head><title>Example Page</title></head>
      <body>
        <p class="title"><b>Sample Page</b></p>
        <p class="story">This is a test story. <a href="http://example.com/1" class="link">link1</a> <a href="http://example.com/2" class="link">link2</a></p>
        <p class="story">Another test story.</p>
      </body>
    </html>
    """
    
    # 使用 BeautifulSoup 解析 HTML 文档
    soup = BeautifulSoup(html_doc, 'html.parser')
    
    # 提取<title>标签的内容
    title = soup.title.string
    print(f"Title: {title}")
    
    # 提取所有的链接(<a> 标签)
    links = soup.find_all('a')
    for link in links:
        print(f"Link text: {link.string}, URL: {link['href']}")
    
    # 查找特定类的<p>标签
    story_paragraphs = soup.find_all('p', class_='story')
    for p in story_paragraphs:
        print(f"Story paragraph: {p.get_text()}")

  • 【HTML】iframe小工具——提取嵌入链接并重设参数

    一般类似YouTube、Bilibili的分享链接,都设置了各自网站的相应参数,为了快速提取其src内容并自定义部分参数,可以使用该小工具进行快速设置。

    操作区
    预览展示区
    查看代码

    <style>
            textarea, input, select {
                width: 100%;
                margin-bottom: 10px;
                padding: 5px;
                font-size: 14px;
            }
            button {
                font-size: 16px;
                margin-bottom: 10px;
                padding: 5px 10px;
            }
            .link-container {
                margin-top: 10px;
            }
            .link-item {
                margin-bottom: 5px;
            }
            .iframe-preview {
                margin-top: 20px;
                padding: 10px;
                border: 1px solid #ddd;
                background: #f9f9f9;
            }
            .iframe-preview pre {
                font-size: 14px;
                background: #e9e9e9;
                padding: 10px;
                border-radius: 5px;
            }
            .row {
                display: flex;
                flex-wrap: wrap;
                gap: 10px;
            }
            .col {
                flex: 1 1 20%;
            }
            .col input, .col select {
                width: 100%;
            }
            .unit-select {
                width: 10px; /*缩小单位选择框宽度*/
            }
            .empty-option {
                font-size: 14px;
            }
            #iframePreviewContainer {
                margin-top: 20px;
            }
        </style>
    </head>
    <body>
        <!-- 输入框 -->
        <textarea id="iframeInput" placeholder="在此输入多个 iframe 代码"></textarea>
        <button id="extractButton">提取链接</button>
    
        <!-- 链接展示区 -->
        <div id="result" class="link-container"></div>
    
        <!-- 单个链接操作区 -->
        <h2>操作区</h2>
        <input id="selectedLink" type="text" placeholder="点击复制按钮后,链接将填入此处" readonly>
        
        <!-- iframe 属性设置 -->
        <div class="row">
            <div class="col">
                <label for="iframeTitle">标题:</label>
                <input id="iframeTitle" type="text" placeholder="请输入 iframe 标题">
            </div>
            <div class="col">
                <label for="iframeWidth">宽度:</label>
                <input id="iframeWidth" type="text" placeholder="例如 560">
            </div>
            <div class="col">
                <label for="iframeWidthUnit">宽度单位:</label>
                <select id="iframeWidthUnit" class="unit-select">
                    <option value="px">px</option>
                    <option value="%">%</option>
                    <option value="vw">vw</option>
                </select>
            </div>
            <div class="col">
                <label for="iframeHeight">高度:</label>
                <input id="iframeHeight" type="text" placeholder="例如 315">
            </div>
            <div class="col">
                <label for="iframeHeightUnit">高度单位:</label>
                <select id="iframeHeightUnit" class="unit-select">
                    <option value="px">px</option>
                    <option value="%">%</option>
                    <option value="vh">vh</option>
                </select>
            </div>
        </div>
    
        <div class="row">
            <div class="col">
                <label for="iframeFullscreen">允许全屏:</label>
                <select id="iframeFullscreen">
                    <option value="allowfullscreen">是</option>
                    <option value="">否</option>
                </select>
            </div>
            <div class="col">
                <label for="iframeReferrer">Referrer Policy:</label>
                <select id="iframeReferrer">
                    <option value="no-referrer">不发送</option>
                    <option value="no-referrer-when-downgrade">仅同源</option>
                    <option value="origin">仅发送源</option>
                    <option value="origin-when-cross-origin">跨源时发送源</option>
                    <option value="same-origin">同源发送完整路径</option>
                    <option value="strict-origin">严格同源发送源</option>
                    <option value="strict-origin-when-cross-origin">默认(严格同源)</option>
                    <option value="unsafe-url">发送完整 URL</option>
                    <option value="">保持空值</option>
                </select>
            </div>
            <div class="col">
                <label for="iframeLoading">加载方式:</label>
                <select id="iframeLoading">
                    <option value="eager">立即加载</option>
                    <option value="lazy">懒加载</option>
                    <option value="">保持空值</option>
                </select>
            </div>
            <div class="col">
                <label for="iframeAutoplay">自动播放:</label>
                <select id="iframeAutoplay">
                    <option value="autoplay">是</option>
                    <option value="">否</option>
                </select>
            </div>
        </div>
    
        <div class="row">
            <div class="col">
                <label for="iframeEncrypted">加密媒体:</label>
                <select id="iframeEncrypted">
                    <option value="encrypted-media">是</option>
                    <option value="">否</option>
                </select>
            </div>
            <div class="col">
                <label for="iframePictureInPicture">画中画:</label>
                <select id="iframePictureInPicture">
                    <option value="picture-in-picture">是</option>
                    <option value="">否</option>
                </select>
            </div>
            <div class="col">
                <label for="iframeWebShare">Web分享:</label>
                <select id="iframeWebShare">
                    <option value="web-share">是</option>
                    <option value="">否</option>
                </select>
            </div>
        </div>
    
        <!-- 生成 iframe 和复制按钮 -->
        <div>
            <button id="generateIframeButton">生成 iframe 嵌入代码</button>
            <button id="copyIframeButton">复制生成代码</button>
        </div>
    
        <!-- iframe 代码展示 -->
        <div id="generatedIframe" class="iframe-preview">
            <textarea id="iframeCodeText" readonly rows="10"></textarea>
        </div>
    
        <!-- iframe 预览展示区 -->
        <div id="iframePreviewContainer" class="iframe-preview">
            <h2>预览展示区</h2>
            <iframe id="iframePreview" src="" width="560" height="315" style="border: none;"></iframe>
        </div>
    
        <script>
            // 缓存常用的 DOM 元素
            const iframeWidthInput = document.getElementById('iframeWidth');
            const iframeHeightInput = document.getElementById('iframeHeight');
            const iframeWidthUnit = document.getElementById('iframeWidthUnit');
            const iframeHeightUnit = document.getElementById('iframeHeightUnit');
            const selectedLinkInput = document.getElementById('selectedLink');
            const iframeFullscreenSelect = document.getElementById('iframeFullscreen');
            const iframeReferrerSelect = document.getElementById('iframeReferrer');
            const iframeLoadingSelect = document.getElementById('iframeLoading');
            const iframeAutoplaySelect = document.getElementById('iframeAutoplay');
            const iframeEncryptedSelect = document.getElementById('iframeEncrypted');
            const iframePictureInPictureSelect = document.getElementById('iframePictureInPicture');
            const iframeWebShareSelect = document.getElementById('iframeWebShare');
            const iframeTitleInput = document.getElementById('iframeTitle');
            const generateIframeButton = document.getElementById('generateIframeButton');
            const copyIframeButton = document.getElementById('copyIframeButton');
            const iframeCodeText = document.getElementById('iframeCodeText');
            const iframePreview = document.getElementById('iframePreview');
            const resultDiv = document.getElementById('result');
    
            // 提取 iframe src 链接
            function extractSrc() {
                const input = document.getElementById('iframeInput').value;
                resultDiv.innerHTML = ''; // 清空之前的结果
    
                const srcMatches = [...input.matchAll(/src="([^"]+)"/g)];
                if (srcMatches.length > 0) {
                    const srcLinks = srcMatches.map(match => match[1]);
    
                    srcLinks.forEach(link => {
                        const linkItem = createLinkItem(link);
                        resultDiv.appendChild(linkItem);
                    });
                } else {
                    resultDiv.textContent = '没有找到有效的 iframe 链接';
                }
            }
    
            // 创建链接项
            function createLinkItem(link) {
                const div = document.createElement('div');
                div.classList.add('link-item');
    
                const textNode = document.createTextNode(link);
                const copyButton = document.createElement('button');
                copyButton.textContent = '复制';
                copyButton.onclick = function() {
                    selectedLinkInput.value = link;
                };
    
                div.appendChild(textNode);
                div.appendChild(copyButton);
                return div;
            }
    
            // 生成 iframe 代码
            function generateIframeCode() {
                const width = iframeWidthInput.value;
                const height = iframeHeightInput.value;
                const widthUnit = iframeWidthUnit.value;
                const heightUnit = iframeHeightUnit.value;
                const title = iframeTitleInput.value;
                const src = selectedLinkInput.value;
                const fullscreen = iframeFullscreenSelect.value;
                const referrer = iframeReferrerSelect.value;
                const loading = iframeLoadingSelect.value;
                const autoplay = iframeAutoplaySelect.value;
                const encrypted = iframeEncryptedSelect.value;
                const pictureInPicture = iframePictureInPictureSelect.value;
                const webShare = iframeWebShareSelect.value;
    
                let iframeCode = `<iframe src="${src}"`;
    
                if (title) {
                    iframeCode += ` title="${title}"`;
                }
                iframeCode += ` width="${width}${widthUnit}" height="${height}${heightUnit}"`;
    
                if (fullscreen) {
                    iframeCode += ` ${fullscreen}`;
                }
    
                if (referrer) {
                    iframeCode += ` referrerpolicy="${referrer}"`;
                }
    
                if (loading) {
                    iframeCode += ` loading="${loading}"`;
                }
    
                if (autoplay) {
                    iframeCode += ` ${autoplay}`;
                }
    
                if (encrypted) {
                    iframeCode += ` ${encrypted}`;
                }
    
                if (pictureInPicture) {
                    iframeCode += ` ${pictureInPicture}`;
                }
    
                if (webShare) {
                    iframeCode += ` ${webShare}`;
                }
    
                iframeCode += '></iframe>';
    
                iframeCodeText.value = iframeCode;
                iframePreview.src = src;
            }
    
            // 复制代码到剪贴板
            function copyIframeCode() {
                iframeCodeText.select();
                document.execCommand('copy');
            }
    
            // 事件监听
            document.getElementById('extractButton').addEventListener('click', extractSrc);
            generateIframeButton.addEventListener('click', generateIframeCode);
            copyIframeButton.addEventListener('click', copyIframeCode);
        </script>
    </body>
  • 【Python】裁切图片为指定画幅比例

    该工具是在截取MTV的画面时产生的需求,一些4:3画幅的视频制作时候加入了黑边,成了16:9视频,因此想截图出原本4:3的画面,一方面可以进剪辑软件进行直接裁剪,也可以在原视频进行导出后操作,考虑到二压费时费力,因此选择对截取的图片进行批处理。

    import os
    import random
    import string
    from tkinter import Tk, filedialog, Button, Label, messagebox
    from PIL import Image
    
    
    def random_filename(extension):
        """生成随机文件名"""
        chars = string.ascii_letters + string.digits
        return ''.join(random.choices(chars, k=8)) + f".{extension}"
    
    
    def crop_to_aspect(image, target_ratio=4/3):
        """裁剪图像宽边以符合指定宽高比"""
        width, height = image.size
        current_ratio = width / height
    
        if current_ratio > target_ratio:  # 如果宽高比大于目标比例,宽度过大
            new_width = int(height * target_ratio)  # 计算符合比例的新宽度
            left = (width - new_width) // 2  # 左侧裁剪量
            right = left + new_width  # 右侧裁剪量
            image = image.crop((left, 0, right, height))  # 裁剪左右宽边
    
        return image
    
    
    def process_images():
        """处理图片并保存结果"""
        input_files = filedialog.askopenfilenames(
            title="选择图片文件",
            filetypes=[("Image Files", "*.jpg *.png")]
        )
        if not input_files:
            return
    
        output_dir = filedialog.askdirectory(title="选择输出文件夹")
        if not output_dir:
            return
    
        for file_path in input_files:
            try:
                with Image.open(file_path) as img:
                    # 转换为符合比例的图片
                    processed_img = crop_to_aspect(img)
                    # 保存文件
                    ext = file_path.split('.')[-1]
                    output_path = os.path.join(output_dir, random_filename(ext))
                    processed_img.save(output_path)
            except Exception as e:
                messagebox.showerror("错误", f"处理文件 {file_path} 时出错: {e}")
                continue
    
        messagebox.showinfo("完成", "图片批量处理完成!")
    
    
    def create_gui():
        """创建GUI"""
        root = Tk()
        root.title("图片批量处理工具")
        root.geometry("400x200")
    
        Label(root, text="批量处理图片 - 保持高度裁切宽边为4:3比例").pack(pady=20)
        Button(root, text="选择图片并处理", command=process_images).pack(pady=10)
        Button(root, text="退出", command=root.quit).pack(pady=10)
    
        root.mainloop()
    
    
    if __name__ == "__main__":
        create_gui()

  • 【HTML】输入Pixiv ID跳转对应画师主页

    Pixiv的应用内部居然没这个功能,不科学,非常基础的功能。

    收录进了小工具页面。👉点击使用小工具

    <body>
        <h1>Pixiv用户跳转</h1>
        <input id="input-id" type="text" placeholder="请输入数字ID" oninput="validateInput()" />
        <div>
            <button onclick="generateLink()">生成链接</button>
            <button onclick="openLink()">跳转</button>
        </div>
        <div id="output"></div>
    
        <script>
            function validateInput() {
                const input = document.getElementById('input-id');
                input.value = input.value.replace(/\D/g, ''); // 只保留数字
            }
    
            function generateLink() {
                const input = document.getElementById('input-id').value.trim();
                const output = document.getElementById('output');
                if (input === '') {
                    output.innerHTML = '<p style="color: red;">请输入有效的数字ID!</p>';
                    return;
                }
                const link = `https://www.pixiv.net/member.php?id=${input}`;
                output.innerHTML = `<a href="${link}" target="_blank">点击跳转到 Pixiv 用户页面</a>`;
            }
    
            function openLink() {
                const input = document.getElementById('input-id').value.trim();
                if (input === '') {
                    alert('您还没有输入ID~');
                    return;
                }
                const link = `https://www.pixiv.net/member.php?id=${input}`;
                window.open(link, '_blank');
            }
        </script>
    </body>
  • 【网站美化】如何为WordPress添加Prism JS代码美化脚本?

    推荐使用Prism.js

    具体方法大神们早已经一笔一划的写出来了

    点击跳转!

    其中通过标签来非全局加载Js的方法非常棒!推荐参考学习。

    本网站则是全局加载JS,通过声明不同的CSS来实现美化效果。

    不加载Prism JS:

       <div class="container">
            <div class="diamond"></div> <!-- 第一个菱形 -->
            <div class="diamond"></div> <!-- 第二个菱形 -->
            <div class="diamond"></div> <!-- 第三个菱形 -->
            <div class="diamond"></div> <!-- 第四个菱形 -->
        </div>

    加载Prism JS:

       <div class="container">
            <div class="diamond"></div> <!-- 第一个菱形 -->
            <div class="diamond"></div> <!-- 第二个菱形 -->
            <div class="diamond"></div> <!-- 第三个菱形 -->
            <div class="diamond"></div> <!-- 第四个菱形 -->
        </div>

    很棒!

  • 【Node.js】批量导出微信联系人到Excel表格(基于Wechaty)

    用到的库:

    wechaty: 一个用于开发微信聊天机器人的框架。

    qrcode-terminal: 用于生成终端二维码的库。

    xlsx: 用于处理 Excel 文件的库。

    fspath: Node.js 的内置文件系统模块,用于文件操作。

    file-box: 用于处理文件(如图片)的库。

    uuid: 用于生成唯一标识符(UUID)的库。

    工作原理:

    基于wechaty的api,获取相应信息并批量导出到excel表格中,头像文件夹单独放置。可以在WPS中依靠UUID生成的唯一ID来快速批量嵌入头像。

    可惜标签功能不在Wechaty的功能中,也没法导出手机号等更有价值的信息,目前能导出的信息不多,图一乐。

    const { WechatyBuilder } = require('wechaty');
    const qrcode = require('qrcode-terminal');
    const xlsx = require('xlsx');
    const fs = require('fs');
    const path = require('path');
    const { FileBox } = require('file-box');
    const { v4: uuidv4 } = require('uuid');  // 引入 UUID 库
    
    const outputDir = './avatars/';  // 存储头像的文件夹
    
    // 确保头像目录存在
    if (!fs.existsSync(outputDir)) {
      fs.mkdirSync(outputDir);
    }
    
    class WeChaty {
      bot = null;
    
      constructor() {
        this.bot = WechatyBuilder.build();
        this.bot.on('scan', code => {
          qrcode.generate(code, { small: true });
        });
        this.bot.on('login', user => {
          console.log(`登录成功,欢迎 ${user}`);
          this.waitForContacts();  // 登录后开始等待联系人同步
        });
      }
    
      // 随机延时函数,返回一个 Promise,用于模拟短时延时
      delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
      }
    
      // 每10秒检查一次联系人数量,最多检查10次
      async waitForContacts() {
        let previousCount = 0;
        let currentCount = 0;
        let attempts = 0;
    
        while (attempts < 10) {
          const allContacts = await this.bot.Contact.findAll();  // 获取所有联系人
          currentCount = allContacts.length;
    
          if (currentCount === previousCount) {
            console.log('联系人数量没有变化,开始导出');
            break;  // 如果联系人数量没有变化,则认为同步完成
          }
    
          console.log(`当前联系人数量: ${currentCount}, 尝试次数: ${attempts + 1}`);
          previousCount = currentCount;
          attempts++;
    
          await this.delay(10000);  // 每次等待10秒再检查
        }
    
        if (attempts >= 10) {
          console.log('尝试多次后联系人数量没有变化,开始导出');
        }
    
        // 导出联系人
        this.getAllFriendContacts();
      }
    
      // 获取所有好友联系人
      async getAllFriendContacts() {
        const allContacts = await this.bot.Contact.findAll();  // 获取所有联系人
    
        // 只筛选出好友联系人
        const friendContacts = allContacts.filter(contact => 
          contact.friend() && contact.type() === this.bot.Contact.Type.Individual
        );
    
        console.log(`总共获取了 ${friendContacts.length} 个好友联系人`);
    
        if (friendContacts.length > 0) {
          await this.exportContacts(friendContacts);  // 导出好友联系人
        }
      }
    
      // 获取并保存联系人头像
      async saveAvatar(contact) {
        try {
          const avatarFile = await contact.avatar();
          if (avatarFile) {
            const cleanName = contact.name().replace(/[\/\\:*?"<>|]/g, '_');  // 清理非法字符
            const uniqueName = `${cleanName}_${uuidv4()}`;  // 使用清理后的昵称 + UUID 作为文件名
            const avatarPath = path.join(outputDir, uniqueName + '.jpg');  // 存储路径
    
            await avatarFile.toFile(avatarPath, true);  // 保存头像文件
            return uniqueName;  // 返回不带后缀的文件名
          }
        } catch (error) {
          console.log(`获取 ${contact.name()} 头像失败`);
        }
        return '';  // 如果获取失败,返回空字符串
      }
    
      // 导出联系人信息
      async exportContacts(allContacts) {
        try {
          const contactList = [];
    
          const avatarPromises = allContacts.map(async (contact) => {
            // 获取头像文件名
            const avatarFileName = await this.saveAvatar(contact);  
    
            // 只导出有头像的联系人,且即使没有昵称也会保留
            return {
              昵称: contact.name().trim() || '无昵称',  // 如果没有昵称,则使用 '无昵称'
              备注: (await contact.alias())?.trim() || '',  // 获取备注信息
              性别: contact.gender() === this.bot.Contact.Gender.Male ? '男' : 
                    contact.gender() === this.bot.Contact.Gender.Female ? '女' : '未知',  // 性别
              省份: contact.province()?.trim() || '',  // 获取省份
              城市: contact.city()?.trim() || '',  // 获取城市
              文件名: avatarFileName,  // 保存文件名(不带后缀)
            };
          });
    
          // 等待所有头像保存完毕
          const contactData = await Promise.all(avatarPromises);
    
          // 使用 xlsx 库导出 Excel 表格
          const ws = xlsx.utils.json_to_sheet(filteredContactData);  // 将联系人信息转换为 Excel 表格
          const wb = xlsx.utils.book_new();  // 创建一个新的 Excel 工作簿
          xlsx.utils.book_append_sheet(wb, ws, '联系人');  // 将联系人数据添加到工作簿
    
          // 将工作簿保存为 Excel 文件
          xlsx.writeFile(wb, 'contacts_with_details.xlsx');
          console.log('好友联系人信息已成功导出到 contacts_with_details.xlsx');
        } catch (error) {
          console.error('导出联系人信息失败:', error);
        }
      }
    
      run() {
        this.bot.start();
      }
    }
    
    new WeChaty().run();
    
  • 【Python】按照关键词查找相应PPT

    今天巧了,好几个同事问我要PPT,但是他们只能记得起来一些关键词,而我恰好也没有很足的印象,毕竟那是两三年前,还可能不是我做的东西!

    WPS只能按照云文档进行查找关键词,那么电脑中几千个PPT要怎么找呢?(没错我电脑里真有2000个PPT (((φ(◎ロ◎;)φ))))

    我们可以根据他们截取的画面关键词,来对PPT进行索引,这样可以节约一些查找文件的时间,然后采用olefile库,查找对应PPT即可。

    import os
    from pptx import Presentation
    import olefile
    
    def is_powerpoint_file(file_path):
        """检查文件是否为PPT或PPTX格式"""
        valid_extensions = ['.ppt', '.pptx']
        return any(file_path.lower().endswith(ext) for ext in valid_extensions)
    
    def index_powerpoint_files(search_dir):
        """索引指定目录中的所有PPT和PPTX文件"""
        ppt_files = []
        total_files = 0
    
        for root, _, files in os.walk(search_dir):
            total_files += len(files)
            for file in files:
                if file.startswith("~$"):  # 跳过临时文件
                    continue
                file_path = os.path.join(root, file)
                if is_powerpoint_file(file_path):
                    ppt_files.append(file_path)
        
        print(f"[信息] 已索引文件总数:{total_files},PPT文件总数:{len(ppt_files)}")
        return ppt_files
    
    def search_text_in_pptx(file_path, target_text):
        """在PPTX文件中搜索目标文字"""
        try:
            presentation = Presentation(file_path)
            for slide in presentation.slides:
                for shape in slide.shapes:
                    if shape.has_text_frame and target_text in shape.text:
                        return True
        except Exception as e:
            print(f"[错误] 无法处理文件:{file_path},错误信息:{e}")
        return False
    
    def search_text_in_ppt(file_path, target_text):
        """在PPT文件中搜索目标文字"""
        try:
            if olefile.isOleFile(file_path):
                with olefile.OleFileIO(file_path) as ole:
                    if "PowerPoint Document" in ole.listdir():
                        stream = ole.openstream("PowerPoint Document")
                        content = stream.read().decode(errors="ignore")
                        if target_text in content:
                            return True
        except Exception as e:
            print(f"[错误] 无法处理文件:{file_path},错误信息:{e}")
        return False
    
    def search_text_in_powerpoint_files(ppt_files, target_text):
        """在索引的PPT文件中搜索目标文字"""
        result_files = []
        total_files = len(ppt_files)
    
        print(f"[信息] 开始内容搜索,共需处理 {total_files} 个文件")
        for idx, file_path in enumerate(ppt_files, start=1):
            print(f"[处理中] {idx}/{total_files} - 正在处理文件:{file_path}")
            if file_path.lower().endswith(".pptx") and search_text_in_pptx(file_path, target_text):
                result_files.append(file_path)
            elif file_path.lower().endswith(".ppt") and search_text_in_ppt(file_path, target_text):
                result_files.append(file_path)
    
        return result_files
    
    if __name__ == "__main__":
        search_dir = "D:\\"
        target_text = input("请输入要查找的文字(支持中文):")
        
        print(f"[信息] 正在索引盘中的PPT文件,请稍候...\n")
        ppt_files = index_powerpoint_files(search_dir)
        
        if ppt_files:
            print(f"\n[信息] 索引完成,开始搜索包含 '{target_text}' 的文件...\n")
            matching_files = search_text_in_powerpoint_files(ppt_files, target_text)
            if matching_files:
                print("\n[结果] 找到包含目标文字的PPT文件:")
                for file in matching_files:
                    print(file)
            else:
                print("\n[结果] 未找到包含该文字的PPT文件。")
        else:
            print("\n[信息] 未在指定目录中找到任何PPT文件。")
    
  • 【Python】对彩色LOGO进行批量反白处理

    为了制作一些高大上的风格化 PPT,有时我们需要很多客户的反白色LOGO,以符合当下的一些设计潮流。

    目前常用的做法是在 PPT中对图片本身进行亮度调整,可以理解为一键过曝,但是这对于一些本身就含有白色的图片不适用,也无法处理JPG的图片,更没法快速将反白的图片进行批量保存,以便存储成库,在其他场景继续使用。

    因此使用脚本可以防止原来的白色部分混成一团,预先对原LOGO白色区域进行透明化,然后对其他颜色区域反白。

    这个脚本目前适用于我的工作环境,包含一些问题,例如如果原来的图标包含白色文字,这样会将其透明化,因此还需按照使用情况进行调整。

    后续考虑加入对JPG进行处理的过程,原理上是对白色部分预先透明度处理,然后后续步骤基本一致,不过使用JPG作为LOGO的客户较少,该功能并不急迫。若要实现该功能,可能需要使用OCR对文字部分预先识别处理,流程上麻烦不少,不过由于wechat-ocr的强大功能,应该也可以稳定呈现,wechat-ocr此前有过一些实践,效果出众,推荐大家使用。

    此外脚本尚未测试灰色部分是否会有问题,目前感觉应该会有问题,若使用中有其他问题会随时更新。

    import tkinter as tk
    from tkinter import filedialog
    from PIL import Image, ImageTk
    import random
    import string
    class ImageProcessor(tk.Tk):
        def __init__(self):
            super().__init__()
            self.title("Logo Image Processor")
            self.geometry("600x600")
            self.image_path = None
            self.images = []  # 用于存储多个图像
            self.image_label = tk.Label(self)
            self.image_label.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
            
            # 设置拖放区域
            self.drop_area = tk.Label(self, text="拖动PNG图片到此区域", relief="solid", width=30, height=4)
            self.drop_area.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
            self.drop_area.bind("<Enter>", self.on_drag_enter)
            self.drop_area.bind("<Leave>", self.on_drag_leave)
            self.drop_area.bind("<ButtonRelease-1>", self.on_drop)
            # 添加处理按钮
            self.process_button = tk.Button(self, text="处理图片并保存", command=self.process_images)
            self.process_button.pack(pady=10)
        def on_drag_enter(self, event):
            self.drop_area.config(bg="lightblue")
        def on_drag_leave(self, event):
            self.drop_area.config(bg="white")
        def on_drop(self, event):
            file_paths = filedialog.askopenfilenames(filetypes=[("PNG files", "*.png")])
            if file_paths:
                self.load_images(file_paths)
        def load_images(self, paths):
            self.images = []  # 清空当前图像列表
            for path in paths:
                image = Image.open(path).convert("RGBA")  # 确保加载为RGBA格式以处理透明度
                self.images.append((path, image))  # 存储图像及其路径
            if self.images:
                self.display_image(self.images[0][1])  # 显示第一张图片
        def display_image(self, image):
            image_tk = ImageTk.PhotoImage(image)
            self.image_label.config(image=image_tk)
            self.image_label.image = image_tk
        def process_images(self):
            if self.images:
                for original_path, image in self.images:
                    # 获取图像的每个像素
                    pixels = image.load()
                    width, height = image.size
                    
                    for x in range(width):
                        for y in range(height):
                            r, g, b, a = pixels[x, y]
                            
                            # 将白色部分透明化
                            if r == 255 and g == 255 and b == 255:
                                pixels[x, y] = (255, 255, 255, 0)  # 将白色变为透明
                            elif a != 0:  # 如果是非透明区域
                                # 将所有非透明区域变为纯白色
                                pixels[x, y] = (255, 255, 255, a)  # 变为白色,保持原透明度
                    
                    # 生成随机字符并保存处理后的图像
                    random_suffix = ''.join(random.choices(string.ascii_letters + string.digits, k=6))
                    output_path = f"processed_logo_{random_suffix}.png"
                    image.save(output_path)
                    print(f"处理后的LOGO图片已保存为 {output_path}")
                    
                # 更新显示处理后的图片(显示第一张图像)
                self.display_image(self.images[0][1])
    if __name__ == "__main__":
        app = ImageProcessor()
        app.mainloop()
    

    此外,还可以对JPG进行处理:

    注意保证输入图片的分辨率,其平滑操作对分辨率会有一定的损失。

    import tkinter as tk
    from tkinter import filedialog, messagebox
    from PIL import Image, ImageFilter
    import random
    import string
    import os
    class ImageProcessor(tk.Tk):
        def __init__(self):
            super().__init__()
            self.title("Logo Image Processor")
            self.geometry("400x200")  # 设置主窗口大小
            self.image_path = None
            self.images = []  # 用于存储多个图像
            self.processed_images = []  # 用于存储处理后图像路径
            # 设置拖放区域
            self.drop_area = tk.Label(self, text="拖动PNG或JPG图片到此区域", relief="solid", width=30, height=4)
            self.drop_area.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
            self.drop_area.bind("<Enter>", self.on_drag_enter)
            self.drop_area.bind("<Leave>", self.on_drag_leave)
            self.drop_area.bind("<ButtonRelease-1>", self.on_drop)
            # 添加处理按钮
            self.process_button = tk.Button(self, text="处理图片并保存", command=self.process_images)
            self.process_button.pack(pady=10)
            # 添加选择输出路径按钮
            self.output_dir = None
            self.select_output_button = tk.Button(self, text="选择保存路径", command=self.select_output_dir)
            self.select_output_button.pack(pady=5)
        def on_drag_enter(self, event):
            self.drop_area.config(bg="lightblue")
        def on_drag_leave(self, event):
            self.drop_area.config(bg="white")
        def on_drop(self, event):
            file_paths = filedialog.askopenfilenames(filetypes=[("Image files", "*.png *.jpg *.jpeg")])
            if file_paths:
                self.load_images(file_paths)
        def load_images(self, paths):
            self.images = []  # 清空当前图像列表
            for path in paths:
                try:
                    image = Image.open(path)
                    # 将JPG图像转换为支持透明度的RGBA格式
                    if image.mode != "RGBA":
                        image = image.convert("RGBA")
                    self.images.append((path, image))  # 存储图像及其路径
                except Exception as e:
                    print(f"无法加载图像 {path}: {e}")
                    messagebox.showerror("错误", f"无法加载图像 {path}")
                    
        def select_output_dir(self):
            self.output_dir = filedialog.askdirectory()
            if self.output_dir:
                print(f"选择的输出目录是: {self.output_dir}")
            
        def process_images(self):
            if not self.images:
                messagebox.showwarning("警告", "请先加载图片")
                return
            
            if not self.output_dir:
                messagebox.showwarning("警告", "请先选择保存路径")
                return
            for original_path, image in self.images:
                pixels = image.load()
                width, height = image.size
                
                for x in range(width):
                    for y in range(height):
                        r, g, b, a = pixels[x, y]
                        
                        # 将接近白色的区域透明化,设置阈值范围 (240, 240, 240) 到 (255, 255, 255)
                        if r >= 240 and g >= 240 and b >= 240:
                            pixels[x, y] = (255, 255, 255, 0)  # 将接近白色的部分变为透明
                        elif a != 0:  # 如果是非透明区域
                            # 将所有非透明区域变为纯白色
                            pixels[x, y] = (255, 255, 255, a)  # 变为白色,保持原透明度
                # 对图像进行边缘平滑处理,减少杂色
                image = image.filter(ImageFilter.GaussianBlur(radius=2))
                
                # 生成随机字符并保存处理后的图像
                random_suffix = ''.join(random.choices(string.ascii_letters + string.digits, k=6))
                output_path = os.path.join(self.output_dir, f"processed_logo_{random_suffix}.png")
                image.save(output_path)
                print(f"处理后的LOGO图片已保存为 {output_path}")
                self.processed_images.append(output_path)
    if __name__ == "__main__":
        app = ImageProcessor()
        app.mainloop()
    

  • 【设计】一种菱形平面的火焰表现形式

    来自索契冬奥会转播画面,应该是俄罗斯国家电视一频道+圣火的标志。

    用HTML粗糙实现类似效果,如果要精准复刻,还是需要位置和动画的精细调整。

    <style>
            /* 创建父容器来承载菱形,并设置其为 relative 定位 */
            .container {
                position: relative;
                width: 500px; /* 缩小容器的大小 */
                height: 500px; /* 缩小容器的大小 */
                display: flex;
                justify-content: center;
                align-items: center;
                overflow: visible; /* 防止容器遮挡菱形动画 */
            }
    
            /* 菱形样式 */
            .diamond {
                position: absolute; /* 使用绝对定位来控制每个菱形的具体位置 */
                width: 60px; /* 缩小菱形的宽度 */
                height: 90px; /* 缩小菱形的高度 */
                background-color: yellow; /* 初始颜色为黄色 */
                clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%); /* 菱形形状 */
                animation: growDiamond 0.5s ease-in-out forwards, 
                          riseAndShrinkDiamond 1.5s ease-in infinite; /* 循环动画 */
                transform-origin: bottom center;
            }
    
            /* 菱形扩展动画 */
            @keyframes growDiamond {
                0% {
                    transform: scaleY(0);
                    opacity: 0;
                }
                100% {
                    transform: scaleY(1);
                    opacity: 1;
                }
            }
    
            /* 上升并缩小动画 */
            @keyframes riseAndShrinkDiamond {
                0% {
                    transform: translateY(0) scale(1);
                    opacity: 1;
                    background-color: yellow;
                }
                100% {
                    transform: translateY(-150px) scale(0.05); /* 缩小菱形的移动范围 */
                    opacity: 0;
                    background-color: red;
                }
            }
    
            /* 为每个菱形设置不同的初始位置、大小、延迟和动画 */
            .diamond:nth-child(1) {
                animation-delay: 0.2s;
                left: 50px; /* 自定义位置 */
                top: 50px;  /* 自定义位置 */
                transform: scale(1.2); /* 初始大小为1.2倍 */
            }
    
            .diamond:nth-child(2) {
                animation-delay: 0.4s;
                left: 60px;
                top: 70px;
                transform: scale(0.8); /* 初始大小为0.8倍 */
            }
    
            .diamond:nth-child(3) {
                animation-delay: 0.6s;
                left: 30px;
                top: 15px;
                transform: scale(1.5); /* 初始大小为1.5倍 */
            }
    
            .diamond:nth-child(4) {
                animation-delay: 0.8s;
                left: 40px;
                top: 20px;
                transform: scale(1);
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="diamond"></div> <!-- 第一个菱形 -->
            <div class="diamond"></div> <!-- 第二个菱形 -->
            <div class="diamond"></div> <!-- 第三个菱形 -->
            <div class="diamond"></div> <!-- 第四个菱形 -->
        </div>
    </body>