首页 > 分享 > 汉字笔画生成

汉字笔画生成

import logging

import os

import re

import time

import flet

from PIL import Image

from flet import (

    Page,

    UserControl,

    Text,

    ListView

)

from flet_core import AlertDialog, TextButton

from playwright.sync_api import sync_playwright 

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

USER_AGENT =

    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'

class ChineseBiHua(UserControl):

    def __init__(self, page: Page, persistent_browser: bool = True):

        super().__init__(page)

        self.page = page

        self.persistent_browser = persistent_browser 

        self.chinese_word_input = flet.TextField(

            label='待输入汉字(可以空格分割;逗号分隔;不加任何符号.)',

            value='无',

            width=615,

            max_lines=5,

            border_radius=10

        )

        self.word_sort_dropdown = flet.Dropdown(

            height=55,

            width=150,

            border_radius=20,

            label="排序",

            text_size=12,

            hint_text="选择需要的顺序",

            value="1",

            options=[

                flet.dropdown.Option(key="1", text="汉字顺序"),

                flet.dropdown.Option(key="2", text="字典顺序"),

            ],

            autofocus=True,

        )

        self.bihua_scroll_viewer = ListView(expand=1, controls=[flet.Image(

            src='./images/笔画总表.png',

            height=600,

            fit=flet.ImageFit.CONTAIN,

        )], height=600, auto_scroll=True)

    def build(self):

        layout = [

            flet.Row(

                controls=[Text("欢迎使用汉字输出笔划工具!", size=30, color=flet.colors.LIGHT_BLUE_500)],

                alignment=flet.MainAxisAlignment.CENTER,

            ),

            flet.Row(controls=[self.chinese_word_input]),

            flet.Row(

                controls=[

                    self.word_sort_dropdown,

                    flet.ElevatedButton(

                        "汉字笔划",

                        height=55,

                        icon=flet.icons.SAVE,

                        on_click=self.generate_bi_hua,

                    ),

                ],

                alignment=flet.MainAxisAlignment.END,

            ),

            flet.Row(controls=[self.bihua_scroll_viewer])

        ]

        return flet.Column(controls=layout)

    def generate_bi_hua(self, e):

        with sync_playwright() as playwright:

            if self.persistent_browser: 

                browser = playwright.chromium.launch(headless=False, args=['--start-maximized'])

                page = browser.new_context(user_agent=USER_AGENT).new_page()

                page.set_viewport_size(viewport_size={'width': 1920, 'height': 1080}) 

            else:

                browser = playwright.chromium.launch_persistent_context( 

                    executable_path=r'C:Program Files (x86)MicrosoftEdgeApplicationmsedge.exe', 

                    channel='msedge', 

                    headless=False,

                    user_data_dir=r"C:UsersAdministratorAppDataLocalMicrosoftEdgeUser DataDefault", 

                    accept_downloads=True,

                    args=['--start-maximized'], 

                    no_viewport=True,

                )

                page = browser.new_page()

            words = re.sub(r'[^u4e00-u9fff]', '', self.chinese_word_input.value)

            logging.info(f'汉字: {words}')

            word_list = list(set(words))

            if self.word_sort_dropdown.value == "2":

                word_list.sort()

            for word in word_list:

                self.generate_single_bi_hua(page, word)

                time.sleep(1)

            concat_images([f'./images/{item}.png' for item in word_list], direction='vertical')

            for item in word_list:

                os.remove(f'./images/{item}.png')

            self.bihua_scroll_viewer.controls.clear() 

            self.bihua_scroll_viewer.controls.append(flet.Image(

                src='./images/合成.png',

                fit=flet.ImageFit.CONTAIN

            ))

            self.bihua_scroll_viewer.update()

            self.show_completion_dialog_and_open_directory()

            browser.close()

    def generate_single_bi_hua(self, page, word):

        url = f"https://hanyu.baidu.com/s?wd={word}&ptype=zici"

        try:

            page.goto(url)

            element_selector = '.word-stroke-wrap'

            page.wait_for_selector(element_selector, timeout=5000)

            element = page.locator(element_selector)

            bounding_box = element.bounding_box()

            logging.info(f'{word}: {bounding_box}')

            if bounding_box:

                x, y, width, height = (bounding_box['x'], bounding_box['y'], bounding_box['width'],

                                       bounding_box['height'])

                page.screenshot(path=f'./images/{word}.png', full_page=True,

                                clip={'x': x, 'y': y, 'width': width, 'height': height})

                time.sleep(0.5)

            else:

                logging.warning(f"{word}没有找到笔划!")

        except Exception as e:

            logging.error(f"{word}生成笔划时发生错误,原因:{e}")

    def show_completion_dialog_and_open_directory(self):

        def close_dlg(e):

            dialog.open = False

            os.startfile(os.path.abspath('./images'))

            self.page.update()

        dialog = AlertDialog(

            title=Text('提示:'),

            actions=[

                TextButton("确定", on_click=close_dlg)

            ],

            actions_alignment=flet.MainAxisAlignment.END,

        )

        self.page.dialog = dialog

        dialog.content = Text('合成图片完成!')

        dialog.open = True

        self.page.update()

def concat_images(images, direction='horizontal', separator_color=(0, 0, 0), separator_size=3):

    images = [Image.open(img) for img in images]

    widths, heights = zip(*(i.size for i in images))

    logging.info(f'widths: {widths}, heights: {heights}')

    if direction == 'horizontal':

        total_width = sum(widths) + separator_size * (len(images) - 1)

        max_height = max(heights)

        new_size = (total_width, max_height)

    else:

        max_width = max(widths)

        total_height = sum(heights) + separator_size * (len(images) - 1)

        new_size = (max_width, total_height)

    new_image = Image.new('RGB', new_size, color=separator_color)

    offset = 0

    for img in images:

        if direction == 'horizontal':

            new_image.paste(img, (offset, 0))

            offset += img.size[0] + separator_size

        else:

            new_image.paste(img, (0, offset))

            offset += img.size[1] + separator_size

    new_image.save('./images/合成.png')

def main(page: flet.Page):

    page.title = "汉字笔画"

    page.window_width = 650

    page.window_height = 850

    page.scroll = True

    page.window_maximizable = False

    page.window_minimized = False

    page.window_center()

    page.update()

    chinese_bihua = ChineseBiHua(page)

    page.add(chinese_bihua)

if __name__ == '__main__':

    flet.app(target=main)

相关知识

《花》字笔画、笔顺、笔划
汉字的演变过程
花组词 分享花字组词语有哪些和花的拼音笔顺笔画怎么写!
花(汉语汉字)
汉字植物课:说说“草”化成“花”生长过程,学习汉字思维并识字
从甲骨文到中山篆铭文,笔画之间有乾坤!来奉博体验汉字的韵与美
在线识别汉字
汉字的由来,汉字的来历和起源
语言,让承载的文明更精彩
汉字演变过程的顺序

网址: 汉字笔画生成 https://m.huajiangbk.com/newsview564979.html

所属分类:花卉
上一篇: excel提取汉字笔画函数,巧妙
下一篇: [tkinter实现]汉字笔顺小