Python Word Automation

python自动化神器专题1:介绍 ​ 本篇主要介绍python自动化开发工具clicknium安装过程以及运行第一个web自动化脚本和第一个桌面自动化脚本。 阅读详情
# generate.py
import win32com.client as win32
from datetime import datetime, date
import re
import os
import sys
import json
import logging
from enumerations import *

logger = logging.getLogger(__name__)
log_formater = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
logger.setLevel(logging.DEBUG)

cmd_handler = logging.StreamHandler(stream=sys.stdout)
cmd_handler.setLevel(logging.DEBUG)
cmd_handler.setFormatter(log_formater)
logger.addHandler(cmd_handler)


def set_log_file(log_file):
    file_handler = logging.FileHandler(filename=log_file, mode='w', encoding='utf-8')
    file_handler.setLevel(logging.INFO)
    # file_handler.addFilter(lambda rec: rec.levelno == logging.INFO)
    file_handler.setFormatter(log_formater)
    logger.addHandler(file_handler)


def search_all(pattern, string):
    search_start = 0
    m = pattern.search(string, pos=search_start)
    rs = []
    while m:
        rs.append(m.group(0))
        search_start = m.end(0) + 1
        m = pattern.search(string, pos=search_start)
    return rs


def package_list_key(item):
    return item[:item.find('.')] + '.pka' if item.endswith('.pks') else item


class Generator:

    def __init__(self, template_filename, task_dir, rel_date, mod_code, prep_by, prep_date, review_by, review_date,
                 summary_list, context_lines=5):
        self.task_dir = task_dir
        self.mod_filename = os.path.join(task_dir, 'MOD_LIST', f'MOD{mod_code[4:]}.docx')
        self.template_filename = template_filename
        self.rel_date = datetime.strptime(rel_date, '%d/%m/%Y').date()
        self.mod_code = mod_code
        self.prep_by = prep_by
        self.prep_date = datetime.strptime(prep_date, '%d/%m/%Y').date() if prep_date is not None else date.today()
        self.review_by = review_by
        self.review_date = datetime.strptime(review_date,
                                             '%d/%m/%Y').date() if review_date is not None else date.today()
        self.summary_list = summary_list
        self.context_lines = context_lines
        self.word = win32.Dispatch('word.Application')
        self.word.visible = True
        try:
            self.document = self.word.Documents.Open(self.template_filename)
        except Exception as e:
            msg = f'ERROR: failed to open template {self.template_filename}'
            logger.error(msg)
            raise e
        else:
            logger.info(f'save as: {self.mod_filename}')
            self.document.SaveAs(self.mod_filename)
            self.section = self.document.sections(1)
            self.range = self.section.Range

    def build_regex_pattern(self,
                            context_lines=0,
                            header_regex='(.*\\n)? *-- Mod. Date.+\\n(^.+\\n).+{mod_code}\\n(^.+\\n)+ *(-+\\n)',
                            line_regex='(.*\\n){{{context_lines}}}.+ -- ?{mod_code}.*\\n(.*\\n){{{context_lines}}}',
                            block_regex='(.*\\n){{{context_lines}}}\\s*--<< ?{mod_code}.*\\n(.*\\n)*?\\s*-->> ?{'
                                        'mod_code}.*\\n(.*\\n){{{context_lines}}}'
                            ):
        header_regex = header_regex.format(mod_code=self.mod_code)
        line_regex = line_regex.format(mod_code=self.mod_code, context_lines=context_lines)
        block_regex = block_regex.format(mod_code=self.mod_code, context_lines=context_lines)
        # logger.info(header_regex)
        # logger.info(line_regex)
        # logger.info(block_regex)
        regex = f'{header_regex}|{line_regex}|{block_regex}'
        return re.compile(pattern=regex, flags=re.MULTILINE)

    def generate(self):
        self.gen_header()
        self.gen_doc_log()
        self.gen_summary()
        self.gen_mod()
        self.document.Save()

    def gen_mod(self):
        logger.info('generate content')
        h3_dict = {
            'Table structure': self.gen_ddl,
            'Table setup': self.gen_dml,
            'Module related': self.gen_plsql,
            'Form related': self.gen_form,
            'Report related': self.gen_report,
            'UNIX related': self.gen_unix,
            'NT related': self.gen_nt,
            'Grant Script related': self.gen_grant
        }
        section = self.document.Sections(1)
        for h3 in h3_dict:
            self.insert_h3(text=h3)
            h3_dict[h3]()

    def gen_header(self):
        logger.info('generate header')
        h = self.section.Headers(WdHeaderFooterIndex.wdHeaderFooterPrimary)
        spaces = ' ' * 90
        header_text = f'HCAS {self.rel_date.strftime("%Y %b")} Release{spaces}{self.mod_code}'
        h.Range.Paragraphs(4).Range.Delete()
        h.Range.InsertParagraphAfter()
        h.Range.Paragraphs(4).Format.Alignment = WdParagraphAlignment.wdAlignParagraphDistribute
        h.Range.Paragraphs(4).Range.Font.Size = 9.5
        h.Range.InsertAfter(header_text)

    def gen_doc_log(self):
        logger.info('generate doc log')
        table = self.document.Tables(1)
        col_1 = table.Columns(2)
        col_2 = table.Columns(4)
        col_1.Cells(1).Range.Text = self.mod_code
        col_1.Cells(2).Range.Text = self.prep_by
        col_1.Cells(3).Range.Text = self.prep_date.strftime('%d/%m/%Y')
        col_2.Cells(1).Range.Text = self.review_by
        col_2.Cells(2).Range.Text = self.review_date.strftime('%d/%m/%Y')

    def gen_summary(self):
        logger.info('generate summary')
        self.range.InsertParagraphAfter()
        last_paragraph_index = self.range.Paragraphs.Count
        self.range.Paragraphs(last_paragraph_index).Style = "Heading 2"
        self.range.InsertAfter('Change Summary')

        for summary in self.summary_list:
            self.range.InsertParagraphAfter()
            if self.range.Paragraphs(last_paragraph_index).Range.ListFormat.ListType != WdListType.wdListBullet:
                last_paragraph_index = self.range.Paragraphs.Count
                self.range.Paragraphs(last_paragraph_index).Range.ListFormat.ApplyBulletDefault()
            self.range.InsertAfter(summary)
        self.insert_normal()
        self.range.InsertParagraphAfter()
        last_paragraph_index = self.range.Paragraphs.Count
        self.range.Paragraphs(last_paragraph_index).Style = "Heading 2"
        self.range.InsertAfter('Mod List')
        self.insert_normal()

    def insert_normal(self):
        self.range.InsertParagraphAfter()
        last_paragraph_index = self.range.Paragraphs.Count
        self.range.Paragraphs(last_paragraph_index).Style = "Normal"

    def insert_normal_text(self, text, target_range=None, add_indent=False):
        if target_range is None:
            target_range = self.range
        target_range.InsertParagraphAfter()
        p_start = target_range.Paragraphs.Count
        target_range.InsertAfter(text)
        p_end = target_range.Paragraphs.Count
        for i in range(p_start, p_end):
            target_range.Paragraphs(i).Style = "Normal"
            target_range.Paragraphs(i).Range.HighlightColorIndex = WdColorIndex.wdNoHighlight
            if add_indent:
                target_range.Paragraphs(i).Indent()

    def insert_highlight_text(self, text, target_range=None, add_indent=False, context_lines=0):
        if target_range is None:
            target_range = self.range
        target_range.InsertParagraphAfter()
        p_start = target_range.Paragraphs.Count
        target_range.InsertAfter(text)
        p_end = target_range.Paragraphs.Count
        for i in range(p_start + context_lines, p_end - context_lines):
            target_range.Paragraphs(p_start).Style = "Normal"
            target_range.Paragraphs(i).Range.HighlightColorIndex = WdColorIndex.wdYellow
            if add_indent:
                target_range.Paragraphs(i).Indent()

    def insert_text(self, text):
        last_paragraph_index = self.range.Paragraphs.Count
        self.range.Paragraphs(last_paragraph_index).Style = "Normal"
        self.range.Paragraphs(last_paragraph_index).Range.HighlightColorIndex = WdColorIndex.wdNoHighlight
        self.range.InsertAfter(text)

    def insert_h3(self, text):
        self.range.InsertParagraphAfter()
        last_paragraph_index = self.range.Paragraphs.Count
        self.range.Paragraphs(last_paragraph_index).Style = "Heading 3"
        self.range.InsertAfter(text)

    def insert_h4(self, text):
        self.range.InsertParagraphAfter()
        last_paragraph_index = self.range.Paragraphs.Count
        self.range.Paragraphs(last_paragraph_index).Style = "Heading 4"
        self.range.InsertAfter(text)

    def insert_list(self, text_list):
        last_paragraph_index = self.range.Paragraphs.Count
        for text in text_list:
            self.range.InsertParagraphAfter()
            if self.range.Paragraphs(last_paragraph_index).Range.ListFormat.ListType != WdListType.wdListBullet:
                last_paragraph_index = self.range.Paragraphs.Count
                self.range.Paragraphs(last_paragraph_index).Range.ListFormat.ApplyBulletDefault()
            self.range.InsertAfter(text)
        self.insert_normal()

    def gen_mod_list(self, source_file, pattern, context_lines=0):
        if not os.path.isfile(source_file):
            msg = f'ERROR: {source_file} is not a file.'
            logger.error(msg)
            raise Exception(msg)
        else:
            logger.info(f'    {source_file}')
            self.insert_normal()
            f = open(file=source_file, encoding='utf-8')
            text = ''.join(f.readlines())
            rs = search_all(pattern=pattern, string=text)
            code_start = self.range.End
            code_range = self.document.Range(code_start - 1, code_start)
            self.document.Tables.Add(code_range, 1, 1)
            code_table = self.document.Tables(self.document.Tables.Count)
            code_table.Borders.Enable = True
            cell_range = code_table.Cell(1, 1).Range
            for r in rs:
                self.insert_normal_text(target_range=cell_range, text='...')
                self.insert_highlight_text(target_range=cell_range, text=r, context_lines=context_lines)
                self.insert_normal_text(target_range=cell_range, text='...')
            f.close()

    def gen_source_list(self, source_dir, pattern, startswith=None, endswith=None, context_lines=0):
        if os.path.isdir(source_dir):
            source_list = list(filter(
                lambda fn: ((startswith is not None and fn.startswith(startswith)) or startswith is None) and (
                            (endswith is not None and fn.endswith(endswith)) or endswith is None),
                os.listdir(source_dir)))
            source_list.sort(key=package_list_key)
            for source_filename in source_list:
                self.insert_h4(text=source_filename)
                src_file = os.path.join(source_dir, source_filename)
                self.gen_mod_list(source_file=src_file, pattern=pattern, context_lines=context_lines)
            return len(source_list)
        else:
            msg = f'{source_dir} not a directory'
            logger.info(msg)
            return 0

    def gen_oracle_like(self, src_dir, startswith=None, endswith=None, context_lines=0):
        p = self.build_regex_pattern(context_lines=context_lines)
        src_cnt = self.gen_source_list(source_dir=src_dir, pattern=p, startswith=startswith, endswith=endswith,
                                       context_lines=context_lines)
        return src_cnt

    def gen_ddsql_like(self, mast_dir, temp_dir, startswith):
        m_cnt = self.gen_oracle_like(src_dir=mast_dir, startswith=startswith, endswith='.sql')
        t_cnt = self.gen_oracle_like(src_dir=temp_dir, startswith=startswith, endswith='.sql')
        if m_cnt == 0 and t_cnt == 0:
            self.insert_list(text_list=('N/A',))

    def gen_dml(self):
        logger.info('    generate dml')
        master_dml_dir = os.path.join(self.task_dir, 'DDSQL')
        temp_dml_dir = os.path.join(master_dml_dir, 'temp')
        self.gen_ddsql_like(mast_dir=master_dml_dir, temp_dir=temp_dml_dir, startswith='DML')

    def gen_ddl(self):
        logger.info('    generate ddl')
        master_ddl_dir = os.path.join(self.task_dir, 'DDSQL')
        temp_ddl_dir = os.path.join(master_ddl_dir, 'temp')
        self.gen_ddsql_like(mast_dir=master_ddl_dir, temp_dir=temp_ddl_dir, startswith='DDL')

    def gen_grant(self):
        logger.info('    generate grant')
        master_grant_dir = os.path.join(self.task_dir, 'DDSQL')
        temp_grant_dir = os.path.join(master_grant_dir, 'temp')
        self.gen_ddsql_like(mast_dir=master_grant_dir, temp_dir=temp_grant_dir, startswith='GRANT')

    def gen_plsql(self):
        logger.info('    generate plsql')
        src_dir = os.path.join(self.task_dir, 'PLSQL')
        src_cnt = self.gen_oracle_like(src_dir=src_dir, context_lines=1)
        if src_cnt == 0:
            self.insert_list(text_list=('N/A',))

    def gen_form(self):
        logger.info('    Form not supported')
        self.insert_list(text_list=('N/A',))

    def gen_report(self):
        logger.info('    Form not supported')
        self.insert_list(text_list=('N/A',))

    def gen_unix(self):
        logger.info('    generate UNIX')
        unix_dir = os.path.join(self.task_dir, 'UNIX_SCRIPT')
        header_regex = '(.*\\n)#.+{mod_code}.+\\n(.*\\n)*# *\\*+\\n'
        line_regex = '(.*\\n){{{context_lines}}}.+ # ?-- ?{mod_code}.*\\n(.*\\n){{{context_lines}}}'
        block_regex = '(.*\\n){{{context_lines}}}\\s*#--<< ?{mod_code}.*\\n(.*\\n)*?\\s*#-->> ?{mod_code}.*\\n(' \
                      '.*\\n){{{context_lines}}}'
        p = self.build_regex_pattern(header_regex=header_regex, block_regex=block_regex, line_regex=line_regex)
        ml12b = os.path.join(unix_dir, 'ML12B')
        count12b = self.gen_source_list(source_dir=ml12b, pattern=p)
        ml16b = os.path.join(unix_dir, 'ML16B')
        count16b = self.gen_source_list(source_dir=ml16b, pattern=p)
        if count12b == 0 and count16b == 0:
            self.insert_list(text_list=('N/A',))

    def gen_nt(self):
        logger.info('    generate NT')
        self.insert_list(text_list=('N/A',))


if __name__ == "__main__":
    args = sys.argv[1:]
    if len(args) == 0:
        workding_dir = os.path.dirname(__file__)
        log_file = os.path.join(workding_dir, 'generate_mod_list.log')
        set_log_file(log_file=log_file)
        conf_file = os.path.join(workding_dir, 'generate_mod_list.json')
        arguments = json.load(open(conf_file, mode='r', encoding='utf-8'))
        g = Generator(**arguments)
        g.generate()
    elif len(args) == 1:
        conf_file = args[0]
        if os.path.isfile(conf_file):
            workding_dir = os.path.dirname(conf_file)
            wrk_log_file = os.path.join(workding_dir, 'generate_mod_list.log')
            set_log_file(log_file=wrk_log_file)
            logger.info(f'Using conf file: {conf_file}')
            arguments = json.load(open(conf_file, mode='r', encoding='utf-8'))
            g = Generator(**arguments)
            g.generate()
        else:
            msg = f'ERROR: {conf_file} is not a file.'
            logger.error(msg)
            raise Exception(msg)
class WdHeaderFooterIndex:
    wdHeaderFooterEvenPages = 3 # Returns all headers or footers on even-numbered pages.
    wdHeaderFooterFirstPage = 2 # Returns the first header or footer in a document or section.
    wdHeaderFooterPrimary = 1 # Returns the header or footer on all pages other than the first page of a document or section.

class WdParagraphAlignment:
    wdAlignParagraphCenter = 1 # Center-aligned.
    wdAlignParagraphDistribute = 4 # Paragraph characters are distributed to fill the entire width of the paragraph.
    wdAlignParagraphJustify = 3 # Fully justified.
    wdAlignParagraphJustifyHi = 7 # Justified with a high character compression ratio.
    wdAlignParagraphJustifyLow = 8 # Justified with a low character compression ratio.
    wdAlignParagraphJustifyMed = 5 # Justified with a medium character compression ratio.
    wdAlignParagraphLeft = 0 # Left-aligned.
    wdAlignParagraphRight = 2 # Right-aligned.
    wdAlignParagraphThaiJustify = 9 # Justified according to Thai formatting layout.


class WdReferenceType:
    wdRefTypeBookmark = 2 # Bookmark.
    wdRefTypeEndnote = 4 # Endnote.
    wdRefTypeFootnote = 3 # Footnote.
    wdRefTypeHeading = 1 # Heading.
    wdRefTypeNumberedItem = 0 # Numbered item.

class WdListType:
    wdListBullet = 2 # Bulleted list.
    wdListListNumOnly = 1 # ListNum fields that can be used in the body of a paragraph.
    wdListMixedNumbering = 5 # Mixed numeric list.
    wdListNoNumbering = 0 # List with no bullets, numbering, or outlining.
    wdListOutlineNumbering = 4 # Outlined list.
    wdListPictureBullet = 6 # Picture bulleted list.
    wdListSimpleNumbering = 3 # Simple numeric list.

class WdColorIndex:
    wdAuto = 0 # Automatic color. Default; usually black.
    wdBlack = 1 # Black color.
    wdBlue = 2 # Blue color.
    wdBrightGreen = 4 # Bright green color.
    wdByAuthor = -1 # Color defined by document author.
    wdDarkBlue = 9 # Dark blue color.
    wdDarkRed = 13 # Dark red color.
    wdDarkYellow = 14 # Dark yellow color.
    wdGray25 = 16 # Shade 25 of gray color.
    wdGray50 = 15 # Shade 50 of gray color.
    wdGreen = 11 # Green color.
    wdNoHighlight = 0 # Removes highlighting that has been applied.
    wdPink = 5 # Pink color.
    wdRed = 6 # Red color.
    wdTeal = 10 # Teal color.
    wdTurquoise = 3 # Turquoise color.
    wdViolet = 12 # Violet color.
    wdWhite = 8 # White color.
    wdYellow = 7 # Yellow color.

class WdBorderType:
    wdBorderBottom = -3 # A bottom border.
    wdBorderDiagonalDown = -7 # A diagonal border starting in the upper-left corner.
    wdBorderDiagonalUp = -8 # A diagonal border starting in the lower-left corner.
    wdBorderHorizontal = -5 # Horizontal borders.
    wdBorderLeft = -2 # A left border.
    wdBorderRight = -4 # A right border.
    wdBorderTop = -1 # A top border.
    wdBorderVertical = -6 # Vertical borders.

如何用 Python 拆分 Word 文件:高效分割大型文档的完整指南 拿我手里这份200页的报告来说,它已经按章节排好版了——第一章、第二章、第三章,每章都从新的一页开始。这种情况下,按“节”拆分最合理,拆出来的每个文件刚好对应一个完整的章节。算一下你的人工成本,如果每个月花几个小时手动拆文档,那几千块的软件授权可能两三个月就回本了。那天下午,我最后用了Aspose.Words的试用版,五分钟拆完了那200页的报告。功能类似,也是商业库,也支持按页、按范围拆分。这个逻辑是:遍历原文档的所有“节”,每次克隆一个节,新建一个空白文档,把克隆的节塞进去,保存。 阅读详情

相关推荐

如何从Excel读取数据,填充到Word模版中,以邮件附件形式群发给多个收件人

如何从Excel读取数据,填充到Word模版中,以邮件附件形式群发给多个收件人

诸神缄默不语的博客 463

自动化:Python、windows、安卓、网页、rpa、autojs、firerpa(抓包逆向ai)

通过VS安装一步到位更省事。如果这个环境变量是空的,uiautomator 将返回 connect_usb,您需要确保只有一个设备连接到计算机。然后就会自动安装库所需要的设备端程序:uiautomator-server,atx-agent,openstf / minicap,openstf / minitouch。因为 run_main 执行的时候,是打印所有用例文件+名称,而通过测试套件 添加 类名称时,执行方式不一样。也可以使用pyautogui库帮助文档的方法,不过本人认为使用上面的方法,更加便利。

freeking101的博客 2万+

霍尔式流量计背后的技术和算法

例如,在一项实验中,当流量低于最小操作范围(0.250 L/min)时,误差比其他流量大,但仍然在95%的精度范围内可接受。例如,在Honeywell电子学的测试中,使用30英寸水柱的压力计和热电偶测量气体特性,记录并计算实际和理论质量流量,以确定修正系数。霍尔式流量计的校准系数是通过一系列精确的测量和计算步骤确定的,以确保其测量结果的准确性和可靠性。霍尔式流量计的校准系数是通过严格的环境条件、精确的测量步骤和实验数据确定的。其中,Qs是标尺介质的流量,K是修正系数,Qm是用户介质的流量。

百态·数智思维 | 聚焦大数据、量化与未来AI 1239

python ui 自动化工具 uiautomation

前言 实习的生活真的就是打杂啊,不是测试人员却要搞着一块东西。开始时带着一点点抗拒慢慢地熟悉起来,后来发现python uiautomation 自动化非常有意思,可以做很多你想象不到的事情,特此记录一下。 简介 uiautomation 是在 GitHub 上的一个开源项目项目地址。总体来说,uiautomation 可以在 windows 平台模拟鼠标和键盘操作。安装的话,可以直接 pip ...

shihunyewu的博客 1万+

模块 stm32_基于STM32设计的RFID读卡模块电路方案(原理图+程序)

采用stm32F030F4,用PWM产生125KHZ的方波,经过推挽电路进行功率放大,高频电流进入LC串联谐振电路,345uH和4.7NF的谐振频率正好是125KHZ,这时电容两端电压会到十几伏。当有卡接近线圈时,线圈两端会有曼彻斯特编码的调幅波。通过二极管以及电容的检波和滤波,产生的小信号送入LM358进行放大和整形,变成单片机可以读取的曼彻斯特编码信号。• IO 分配(采用内部晶...

weixin_28686771的博客 3819

ChatUI vs Ant Design X 技术选型对比

维度ChatUI优势轻量级、易上手、完美兼容 Ant Design全能型框架、企业级扩展性、深度模型集成局限性功能单一、缺乏高级交互支持学习曲线陡峭、包体积较大最佳实践单独聊天窗口集成整体智能助手系统开发通过对比可见,ChatUI 适合快速实现基础对话功能,而Ant Design X 更适合构建复杂的 AI 驱动应用。实际选择时需结合项目规模、团队技术栈和对交互复杂度的需求综合评估。

四楼没电梯的专栏 2269

全面讲解python的uiautomation包

在常规的模拟鼠标和键盘操作,我们一般使用,uiautomation模块不仅能直接支持这些操作,还能通过控件定位方式直接定位到目标控件的位置,而不需要自己去获取对应坐标位置。uiautomation模块不仅支持任意坐标位置截图,还支持目标控件的截图,缺点在于截取产生的图片对象难以直接与PIL库配合,只能导出文件后让PIL图像处理库重新读取。对于能够获取到其ScrollItemPattern对象的控件还可以通过ScrollIntoView方法进行视图定位,与浏览器的元素定位效果几乎一致。

JineD的博客 5290

Codex CLI 接入智谱 GLM-5.1 完整教程

Codex CLI 是 OpenAI 推出的命令行 AI 编程工具,支持自主读取文件、执行命令、编写代码等操作,是目前最火的终端 AI 编程工具之一。通过 CLIProxyAPI 代理,我们成功将 Codex CLI 与智谱 GLM-5.1 模型对接,核心在于解决 Responses API 与 Chat Completions API 的协议转换问题。✅成熟稳定:CLIProxyAPI 社区活跃(4.7k fork),持续维护✅完整兼容:支持流式/非流式、function calling✅低成本。

u011831527的博客 2584

Python的UI操作——UiAutomation 库

自动化测试:UiAutomation 库可以帮助开发人员编写自动化测试脚本,通过模拟用户操作和验证应用程序的行为来进行自动化测试。通过菜单项的名称为"Save as"来查找并点击对应的元素。你提供的代码使用了 UiAutomation 库的一些常见方法来操作应用程序中的元素。分别通过按钮、超链接和文本控件的名称为"确定"来查找并点击对应的元素。通过拆分按钮的本地化控件类型为"拆分按钮"来查找并点击对应的元素。通过文档的本地化控件类型为"文档"来查找并点击对应的元素。来点击一个名为 “账户” 的编辑框。

m0_57021623的博客 7383

手把手学计科--web网页设计

网页的组成:文字、图像和超链接等元素。还可以包括哦音频、视频和动画。分类:静态(固定信息)和动态(与服务器数据库进行实时的数据交换。HTML和CSS 是一种静态网页搭建技术。

Yhvaely的博客 1755

《Autosar从入门到精通-实战篇》总目录_培训教程持续更新中...

欢迎大家订阅《Autosar从入门到精通-实战篇》,下方整理了相关博文的目录(单击蓝色字体即可跳转),方便大家获取。 本专栏旨在:扫除Autosar工具链配置过程中的障碍,加深对Autosar理论的理解。 温馨提醒: 如有疑问,可在博文的“评论区”给小编留言,进行技术交流(评论区开启了验证功能,审核通过后,会显示); 如有疑问,也可以通过博文中的第一个图片联系小编,获取专栏/博文的实时状态; 由于工作限制,仅做个人技术交流。添加好友时,请备注您的“姓名-公司-职务...

「汽车电子助手」的博客 12万+

Python+PSCAD自动化实战:3种方法教你高效保存仿真波形到Word文档(附代码)

本文详细介绍了使用Python和PSCAD自动化库高效保存仿真波形到Word文档的3种实用方法,包括基础截图法、批量导出法和动态生成法。通过代码示例和实战技巧,帮助电力系统仿真工程师大幅提升工作效率,实现波形数据的自动化处理与报告生成。

gan8painter的博客 230

【云原生技术】sonar的官方web接口,获取质量阀结果的接口

以下是一个示例思路,说明如何调用 SonarQube 的质量阀查询接口并在前端展示“哪些条件没过”。假设前端使用 AJAX 或 fetch 从后端接口拿到 SonarQube 返回的 JSON(或直接前端请求 SonarQube API),前端再把解析结果展示给用户。测试覆盖率 (Coverage) 当前仅有 60%,未满足最低 80% 的要求,需要补充测试或优化以提升覆盖率。接口),就会返回相应的质量阀状态信息;里使用它来查询当前质量阀(质量门)的状态。,你用它即可获取该次分析的质量阀状态。

weixin_46453070的博客 1282

python 替换word内容 doc转换成docx

【代码】python 替换word内容。

weixin_43661313的博客 815

Transformer实战(38)——视觉Transformer (Vision Transformer, ViT)

Transformer 在自然语言处理 (NLP) 领域取得了显著成就,在许多不同的任务中都表现出色。在本节中,我们将探索视觉 Transformer (Vision Transformer, ViT) 模型。正如 NLP 领域创建了多种模型一样,视觉领域也开发了多种模型,每种模型都为计算机视觉提供了新的视角。通过本节,将学习如何使用 ViT 等模型进行计算机视觉任务,了解基于 Transformer 的预训练计算机视觉模型的工作原理,以及如何针对特定任务进行微调。

盼小辉丶的博客 2951

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

pythondocx更新目录,Python:创建“目录”使用python-docx / lxml

I'm trying to automate the creation of .docx files (WordML) with the help of python-docx (https://github.com/mikemaccana/python-docx). My current script creates the ToC manually with following loop:fo...

weixin_42300194的博客 751

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

python修改word_Python win32com-自动Word-如何替换文本框中的文本?

我正在尝试使用Python自动执行单词替换word文档中的文本. (如果重要的话,我使用Word 2003和Python 2.4)下面我的replace方法的第一部分适用于除文本框中的文本以外的所有内容.文本只是没有被选中.我注意到当我手动进入Word并按ctrl-A时,除文本框外,所有文本均被选中.到目前为止,这是我的代码:class Word:def __init__(self,visible...

weixin_39866774的博客 634

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

python批量读取word表格写入excel固定位置

本文介绍了一个自动化处理Word和Excel文件的Python脚本。该脚本主要功能是从指定目录查找.docx格式的Word文件,提取其中特定表格数据,并将这些数据写入Excel模板的指定单元格中。脚本使用os模块遍历目录,docx库读取Word表格数据,openpyxl库操作Excel文件,实现了权利人信息、不动产编号等关键数据的自动提取和填充。最后将处理后的Excel文件以"不动产单元号+filled_template.xlsx"的格式保存。文章详细说明了代码的各功能模块,并提出了添加

学习与分享 634

python能做word和excel吗_Python 操作Word(Excel、PPT等通用)

使用技巧import win32comfrom win32com.client import Dispatch, constantsw = win32com.client.Dispatch('Word.Application')# 或者使用下面的方法,使用启动独立的进程:# w = win32com.client.DispatchEx('Word.Application')# 后台运行,不显示,不...

weixin_32050033的博客 331

python读取word文件并替换部分文字,Python win32com-自动Word-如何替换文本框中的文本?...

I'm trying to automate word to replace text in a word document using Python. (I'm on word 2003 if that matters and Python 2.4)The first part of my replace method below works on everything except text...

weixin_29973493的博客 409

【文件处理】【libreoffice】 python 操作word及excel文档

1、开始、关闭libreoffice服务; 开始之前同步字体文件时间,是因为创建soffice服务时,服务会检查所需加载的文件的时间,如果其认为时间不符,则其可能会重新加载,耗时较长,因此需事先统一时间。 使用时如果需要多次调用,最后每次调用均开启后关闭,否则libreoffice会创建一个缓存文档并越用越大,处理时间会增加。 class OfficeProcess(object): def __init__(self): self.p = 0 subproc

走在搬砖的路上! 2283

python实现markdown转word文档

本文介绍了一个批量Markdown转Word的Python程序,使用tkinter构建GUI界面。程序核心功能包括:1) 将单个.md文件转换为.docx格式;2) 支持标题、段落、列表、代码块和表格等Markdown元素转换;3) 提供多文件选择功能(Ctrl多选);4) 显示转换成功/失败统计。转换过程使用markdown和BeautifulSoup库解析内容,通过python-docx库生成Word文档。程序界面简洁,包含操作提示和反馈机制。

流浪猫 159

Python 设置word属性的函数

office2007中不能直接打开VB编辑器,请按Alt+F11Alt+F11Alt+F11Alt+F11打开。 importwin32com.client#导入脚本模块 WordApp=win32com.client.Dispatch("Word.Application")#载入WORD模块 WordApp.Visible=True#...

weixin_30741653的博客 799

OfficeAutomation——Task03 python自动化之word操作

python自动化之word操作 1.课前准备 2.知识要点 2.1初步认识docx 2.1.1新建空白word并插入文字 2.2python自动化之word操作 2.2.1整体页面结构介绍 2.2.2字体设置 2.2.3插入图片与表格 2.2.4设置页眉页脚 2.2.5代码延伸 3.项目实践 3.1需求 3.2需求分析 ...

m0_46228848的博客 225

使用 Python 高效提取 Word 文档的特定页 (连续页、不连续页、按页拆分)

使用 Python 提取 Word 页面,是办公自动化中比较实用的一类需求,常见于报告拆分、内容截取以及文档归档等场景。本文主要介绍了三种典型的页面提取方式:提取单页或连续页面,用于快速截取文档中的指定内容;提取不连续页面,用于从文档中筛选特定页并重新组合;以及按页拆分整个 Word 文档,将每一页保存为独立文件,便于后续管理与分发。通过这些方法,可以在不破坏原有排版的前提下,更灵活地对 Word 文档进行页面级处理,使其在实际自动化流程中更接近 PDF 的操作方式。

SunnyDays1011的博客 841

向word中持续追加内容(图片)

【代码】向word中持续追加内容(图片)

weixin_44971645的博客 25
上一篇: Oracle query table space statistics
下一篇: Python Create EPUB
DataPeak
博客等级 码龄15年 32粉丝 68原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值