使用 Python 自动化 Word 文档样式复制与内容生成

在办公自动化领域,如何高效地处理 Word 文档的样式和内容复制是一个常见需求。本文将通过一个完整的代码示例,展示如何利用 Python 的 python-docx 库实现 Word 文档样式的深度复制动态内容生成,并结合知识库中的最佳实践优化文档处理流程。


一、为什么需要自动化 Word 文档处理?

手动处理 Word 文档(如复制样式、插入表格/图片)不仅耗时且容易出错。Python 提供了多种库(如 python-docxpywin32Spire.Doc)来自动化这些任务。例如,python-docx 可以直接操作 .docx 文件的段落、表格和样式,而无需依赖 Microsoft Office 软件。


二、核心功能实现:样式与表格的深度复制

1. 表格复制(含样式与内容)

以下函数 clone_table 实现了表格的 结构、样式和内容 的完整复制:

def clone_table(old_table, new_doc):"""根据旧表格创建新表格"""# 创建新表格(行列数与原表一致)new_table = new_doc.add_table(rows=len(old_table.rows), cols=len(old_table.columns))# 复制表格样式(如边框、背景色)if old_table.style:new_table.style = old_table.style# 遍历单元格内容与样式for i, old_row in enumerate(old_table.rows):for j, old_cell in enumerate(old_row.cells):new_cell = new_table.cell(i, j)# 清空新单元格默认段落for paragraph in new_cell.paragraphs:new_cell._element.remove(paragraph._element)# 复制段落与样式for old_paragraph in old_cell.paragraphs:new_paragraph = new_cell.add_paragraph()for old_run in old_paragraph.runs:new_run = new_paragraph.add_run(old_run.text)copy_paragraph_style(old_run, new_run)  # 自定义样式复制函数new_paragraph.alignment = old_paragraph.alignmentcopy_cell_borders(old_cell, new_cell)  # 复制单元格边框# 复制列宽for i, col in enumerate(old_table.columns):if col.width is not None:new_table.columns[i].width = col.widthreturn new_table
关键点解析:
  • 表格样式保留:通过 new_table.style = old_table.style 直接继承原表格的样式。
  • 单元格内容与格式分离处理:先清空新单元格的默认段落,再逐行复制文本和样式。
  • 边框与列宽:通过 copy_cell_borders 和列宽设置确保视觉一致性。

2. 文档整体样式复制与内容生成

以下函数 clone_document 实现了从模板文档提取样式,并动态填充内容:

def clone_document(old_s, old_p, old_ws, new_doc_path):new_doc = Document()  # 创建新文档# 动态填充内容for para in old_p:k, v = para["sn"], para["ct"]  # 假设 old_p 包含样式名(sn)和内容(ct)if "image" in v:# 插入图片(需实现 copy_inline_shapes 函数)copy_inline_shapes(new_doc, k, [i for i in old_s if v in i][0][v])elif "table" == k:# 插入表格(需实现 html_table_to_docx 函数)html_table_to_docx(new_doc, v)else:# 段落处理style = [i for i in old_s if i["style"]["sn"] == k]style_ws = [i for i in old_ws if i["style"]["sn"] == k]clone_paragraph(style[0], v, new_doc, style_ws[0])  # 克隆段落样式new_doc.save(new_doc_path)  # 保存新文档
数据结构说明:
  • old_s:模板文档的样式定义(如字体、段落对齐方式)。
  • old_p:内容数据(含样式标签与实际内容)。
  • old_ws:工作表上下文(如表格所在位置)。

三、完整流程演示

1. 依赖准备

首先安装 python-docx

pip install python-docx

2. 辅助函数实现

以下函数需额外实现(代码未展示完整):

  • copy_paragraph_style:复制段落样式(如字体、颜色)。
  • copy_cell_borders:复制单元格边框样式。
  • get_para_style:从模板文档提取样式。
  • html_table_to_docx:将 HTML 表格转换为 Word 表格。

3. 主程序调用

if __name__ == "__main__":# 从模板提取样式与工作表body_ws, _ = get_para_style('demo_template.docx')body_s, body_p = get_para_style("1.docx")# 从 JSON 文件加载内容with open("1.json", "r", encoding="utf-8") as f:body_p = json.loads(f.read())# 生成新文档clone_document(body_s, body_p, body_ws, 'cloned_example.docx')

四、实际应用场景

  1. 报告自动生成
    结合模板样式,动态填充数据库数据生成标准化报告。

  2. 批量文档处理
    将多个 Excel 表格批量转换为 Word 文档(参考知识库中的 pywin32python-docx 联合使用)。

  3. 博客内容迁移
    将 Word 文档保存为 HTML 后,按知识库中的步骤导入 ZBlog 或 WordPress(见知识库 [2] 和 [5])。


五、常见问题与优化建议

1. 样式丢失问题

  • 原因:Word 文档的样式可能依赖隐式继承。
  • 解决方案:使用 python-docxstyle 属性显式设置样式,或参考知识库 [7] 使用 Spire.Doc 进行更复杂的样式处理。

2. 图片与表格嵌入异常

  • 原因:路径错误或资源未正确加载。
  • 解决方案:确保图片路径绝对化,或使用 docx.shared.Inches 显式指定尺寸。

3. 性能优化

  • 大文档处理:避免频繁调用 add_paragraph,改用批量操作。
  • 内存管理:及时释放 Document 对象(如 doc = None)。

六、总结

通过本文的代码示例和解析,您已掌握如何使用 Python 实现 Word 文档的 样式深度复制动态内容生成。结合知识库中的其他技术(如 ZBlog 导入、Office 自动化),可进一步扩展至完整的文档工作流自动化。

希望这篇博客能帮助您高效实现文档自动化!如需进一步优化或功能扩展,欢迎留言讨论。

from docx.enum.text import WD_BREAKfrom docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml import OxmlElement
from bs4 import BeautifulSoupfrom docx.oxml.ns import qndef docx_table_to_html(word_table):soup = BeautifulSoup(features='html.parser')html_table = soup.new_tag('table', style="border-collapse: collapse;")# 记录哪些单元格已经被合并merged_cells = [[False for _ in range(len(word_table.columns))] for _ in range(len(word_table.rows))]for row_idx, row in enumerate(word_table.rows):html_tr = soup.new_tag('tr')col_idx = 0while col_idx < len(row.cells):cell = row.cells[col_idx]# 如果该单元格已经被合并(被前面的 colspan 或 rowspan 占用),跳过if merged_cells[row_idx][col_idx]:col_idx += 1continue# 跳过纵向合并中被“continue”的单元格v_merge = cell._element.tcPr and cell._element.tcPr.find(qn('w:vMerge'))if v_merge is not None and v_merge.get(qn('w:val')) == 'continue':col_idx += 1continuetd = soup.new_tag('td')# 设置文本内容td.string = cell.text.strip()# 初始化样式字符串td_style = ''# 获取单元格样式if cell._element.tcPr:tc_pr = cell._element.tcPr# 处理背景颜色shd = tc_pr.find(qn('w:shd'))if shd is not None:bg_color = shd.get(qn('w:fill'))if bg_color:td_style += f'background-color:#{bg_color};'# 处理对齐方式jc = tc_pr.find(qn('w:jc'))if jc is not None:align = jc.get(qn('w:val'))if align == 'center':td_style += 'text-align:center;'elif align == 'right':td_style += 'text-align:right;'else:td_style += 'text-align:left;'# 处理边框borders = tc_pr.find(qn('w:tcBorders'))if borders is not None:for border_type in ['top', 'left', 'bottom', 'right']:border = borders.find(qn(f'w:{border_type}'))if border is not None:color = border.get(qn('w:color'), '000000')size = int(border.get(qn('w:sz'), '4'))  # 半点单位,1pt = 2szstyle = border.get(qn('w:val'), 'single')td_style += f'border-{border_type}:{size // 2}px {style} #{color};'# 处理横向合并(colspan)grid_span = tc_pr.find(qn('w:gridSpan'))if grid_span is not None:colspan = int(grid_span.get(qn('w:val'), '1'))if colspan > 1:td['colspan'] = colspan# 标记后面被合并的单元格for c in range(col_idx + 1, col_idx + colspan):if c < len(row.cells):merged_cells[row_idx][c] = True# 处理纵向合并(rowspan)v_merge = tc_pr.find(qn('w:vMerge'))if v_merge is not None and v_merge.get(qn('w:val')) != 'continue':rowspan = 1next_row_idx = row_idx + 1while next_row_idx < len(word_table.rows):next_cell = word_table.rows[next_row_idx].cells[col_idx]next_v_merge = next_cell._element.tcPr and next_cell._element.tcPr.find(qn('w:vMerge'))if next_v_merge is not None and next_v_merge.get(qn('w:val')) == 'continue':rowspan += 1next_row_idx += 1else:breakif rowspan > 1:td['rowspan'] = rowspan# 标记后面被合并的行for r in range(row_idx + 1, row_idx + rowspan):if r < len(word_table.rows):merged_cells[r][col_idx] = True# 设置样式和默认边距td['style'] = td_style + "padding: 5px;"html_tr.append(td)# 更新列索引if 'colspan' in td.attrs:col_idx += int(td['colspan'])else:col_idx += 1html_table.append(html_tr)soup.append(html_table)return str(soup)def set_cell_background(cell, color_hex):"""设置单元格背景色"""color_hex = color_hex.lstrip('#')shading_elm = OxmlElement('w:shd')shading_elm.set(qn('w:fill'), color_hex)cell._tc.get_or_add_tcPr().append(shading_elm)def html_table_to_docx(doc, html_content):"""将 HTML 中的表格转换为 Word 文档中的表格:param html_content: HTML 字符串:param doc: python-docx Document 实例"""soup = BeautifulSoup(html_content, 'html.parser')tables = soup.find_all('table')for html_table in tables:# 获取表格行数trs = html_table.find_all('tr')rows = len(trs)# 估算最大列数(考虑 colspan)cols = 0for tr in trs:col_count = 0for cell in tr.find_all(['td', 'th']):col_count += int(cell.get('colspan', 1))cols = max(cols, col_count)# 创建 Word 表格table = doc.add_table(rows=rows, cols=cols)table.style = 'Table Grid'# 记录已处理的单元格(用于处理合并)used_cells = [[False for _ in range(cols)] for _ in range(rows)]for row_idx, tr in enumerate(trs):cells = tr.find_all(['td', 'th'])col_idx = 0for cell in cells:while col_idx < cols and used_cells[row_idx][col_idx]:col_idx += 1if col_idx >= cols:break  # 避免越界# 获取 colspan 和 rowspancolspan = int(cell.get('colspan', 1))rowspan = int(cell.get('rowspan', 1))# 获取文本内容text = cell.get_text(strip=True)# 获取对齐方式align = cell.get('align')align_map = {'left': WD_ALIGN_PARAGRAPH.LEFT,'center': WD_ALIGN_PARAGRAPH.CENTER,'right': WD_ALIGN_PARAGRAPH.RIGHT}# 获取背景颜色style = cell.get('style', '')bg_color = Nonefor s in style.split(';'):if 'background-color' in s or 'background' in s:bg_color = s.split(':')[1].strip()break# 获取 Word 单元格word_cell = table.cell(row_idx, col_idx)# 合并单元格if colspan > 1 or rowspan > 1:end_row = min(row_idx + rowspan - 1, rows - 1)end_col = min(col_idx + colspan - 1, cols - 1)merged_cell = table.cell(row_idx, col_idx).merge(table.cell(end_row, end_col))word_cell = merged_cell# 设置文本内容para = word_cell.paragraphs[0]para.text = text# 设置对齐方式if align in align_map:para.alignment = align_map[align]# 设置背景颜色if bg_color:try:set_cell_background(word_cell, bg_color)except:pass  # 忽略无效颜色格式# 标记已使用的单元格for r in range(row_idx, min(row_idx + rowspan, rows)):for c in range(col_idx, min(col_idx + colspan, cols)):used_cells[r][c] = True# 移动到下一个可用列col_idx += colspan# 添加空段落分隔doc.add_paragraph()return docdef copy_inline_shapes(old_paragraph):"""复制段落中的所有内嵌形状(通常是图片)"""images = []for shape in old_paragraph._element.xpath('.//w:drawing'):blip = shape.find('.//a:blip', namespaces={'a': 'http://schemas.openxmlformats.org/drawingml/2006/main'})if blip is not None:rId = blip.attrib['{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed']image_part = old_paragraph.part.related_parts[rId]image_bytes = image_part.image.blobimage_name=image_part.filename+";"+image_part.partnameimages.append([image_bytes,image_name, image_part.image.width, image_part.image.height])return imagesdef is_page_break(element):"""判断元素是否为分页符(段落或表格后)"""if element.tag.endswith('p'):for child in element:if child.tag.endswith('br') and child.get(qn('type')) == 'page':return Trueelif element.tag.endswith('tbl'):# 表格后可能有分页符(通过下一个元素判断)if element.getnext() is not None:next_element = element.getnext()if next_element.tag.endswith('p'):for child in next_element:if child.tag.endswith('br') and child.get(qn('type')) == 'page':return Truereturn Falsedef clone_paragraph(old_para):"""根据旧段落创建新段落"""style = {"run_style": []}if old_para.style:# 这里保存style  主要通过字体识别   是 几级标题style_name_to_style_obj = {"sn":old_para.style.name + "_" + str(old_para.alignment).split()[0], "ct": old_para.style}style["style"] = style_name_to_style_objparas = []for old_run in old_para.runs:text_to_style_name = {"ct":old_run.text, "sn":old_para.style.name + "_" + str(old_para.alignment).split()[0]}style["run_style"].append(old_run)paras.append(text_to_style_name)style_name_to_alignment = {"sn":old_para.style.name + "_" + str(old_para.alignment).split()[0],"ct":old_para.alignment}style["alignment"] = style_name_to_alignmentimages = copy_inline_shapes(old_para)if len(images):for  image_bytes,image_name, image_width, image_height in images:style[image_name.split(";")[-1]] = imagesparas.append({"sn":image_name.split(";")[0],"ct":image_name.split(";")[-1]})return style, parasdef clone_document(old_doc_path):try:old_doc = Document(old_doc_path)new_doc = Document()# 复制主体内容elements = old_doc.element.bodypara_index = 0table_index = 0index = 0body_style = []body_paras = []while index < len(elements):element = elements[index]if element.tag.endswith('p'):old_para = old_doc.paragraphs[para_index]style, paras = clone_paragraph(old_para)body_style.append(style)body_paras += paraspara_index += 1index += 1elif element.tag.endswith('tbl'):old_table = old_doc.tables[table_index]body_paras += [{"sn":"table","ct":docx_table_to_html(old_table)}]table_index += 1index += 1elif element.tag.endswith('br') and element.get(qn('type')) == 'page':if index > 0:body_paras.append("br")new_doc.add_paragraph().add_run().add_break(WD_BREAK.PAGE)index += 1else:index += 1# 检查分页符if index < len(elements) and is_page_break(elements[index]):if index > 0:new_doc.add_paragraph().add_run().add_break(WD_BREAK.PAGE)body_paras.append("br")index += 1else:return body_style, body_parasexcept Exception as e:print(f"复制文档时发生错误:{e}")# 使用示例
if __name__ == "__main__":# 示例HTML表格body_s, body_p = clone_document('1.docx')print()
import jsonfrom docx import Document
from docx.oxml import OxmlElement
from docx.oxml.shared import qn
from wan_neng_copy_word import clone_document as get_para_style,html_table_to_docx
import io
# 剩余部分保持不变...def copy_inline_shapes(new_doc,image_name, img):"""复制段落中的所有内嵌形状(通常是图片)"""new_para = new_doc.add_paragraph()for image_bytes_src,_, w, h in img:try:with open(image_name, 'rb') as f:image_bytes = f.read()except:image_bytes = image_bytes_src# 添加图片到新段落new_para.add_run().add_picture(io.BytesIO(image_bytes), width=w, height=h)  # 设置宽度为1.25英寸或其他合适的值def copy_paragraph_style(run_from, run_to):"""复制 run 的样式"""run_to.bold = run_from.boldrun_to.italic = run_from.italicrun_to.underline = run_from.underlinerun_to.font.size = run_from.font.sizerun_to.font.color.rgb = run_from.font.color.rgbrun_to.font.name = run_from.font.namerun_to.font.all_caps = run_from.font.all_capsrun_to.font.strike = run_from.font.strikerun_to.font.shadow = run_from.font.shadowdef is_page_break(element):"""判断元素是否为分页符(段落或表格后)"""if element.tag.endswith('p'):for child in element:if child.tag.endswith('br') and child.get(qn('type')) == 'page':return Trueelif element.tag.endswith('tbl'):# 表格后可能有分页符(通过下一个元素判断)if element.getnext() is not None:next_element = element.getnext()if next_element.tag.endswith('p'):for child in next_element:if child.tag.endswith('br') and child.get(qn('type')) == 'page':return Truereturn Falsedef clone_paragraph(para_style, text, new_doc, para_style_ws):"""根据旧段落创建新段落"""new_para = new_doc.add_paragraph()para_style_ws = para_style_ws["style"]["ct"]para_style_data = para_style["style"]["ct"]para_style_ws.font.size = para_style_data.font.sizenew_para.style = para_style_wsnew_run = new_para.add_run(text)copy_paragraph_style(para_style["run_style"][0], new_run)new_para.alignment = para_style["alignment"]["ct"]return new_paradef copy_cell_borders(old_cell, new_cell):"""复制单元格的边框样式"""old_tc = old_cell._tcnew_tc = new_cell._tcold_borders = old_tc.xpath('.//w:tcBorders')if old_borders:old_border = old_borders[0]new_border = OxmlElement('w:tcBorders')border_types = ['top', 'left', 'bottom', 'right', 'insideH', 'insideV']for border_type in border_types:old_element = old_border.find(f'.//w:{border_type}', namespaces={'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'})if old_element is not None:new_element = OxmlElement(f'w:{border_type}')for attr, value in old_element.attrib.items():new_element.set(attr, value)new_border.append(new_element)tc_pr = new_tc.get_or_add_tcPr()tc_pr.append(new_border)def clone_table(old_table, new_doc):"""根据旧表格创建新表格"""new_table = new_doc.add_table(rows=len(old_table.rows), cols=len(old_table.columns))if old_table.style:new_table.style = old_table.stylefor i, old_row in enumerate(old_table.rows):for j, old_cell in enumerate(old_row.cells):new_cell = new_table.cell(i, j)for paragraph in new_cell.paragraphs:new_cell._element.remove(paragraph._element)for old_paragraph in old_cell.paragraphs:new_paragraph = new_cell.add_paragraph()for old_run in old_paragraph.runs:new_run = new_paragraph.add_run(old_run.text)copy_paragraph_style(old_run, new_run)new_paragraph.alignment = old_paragraph.alignmentcopy_cell_borders(old_cell, new_cell)for i, col in enumerate(old_table.columns):if col.width is not None:new_table.columns[i].width = col.widthreturn new_tabledef clone_document(old_s, old_p, old_ws, new_doc_path):new_doc = Document()# 复制主体内容for para in old_p:k, v =para["sn"],para["ct"]if "image" in v:copy_inline_shapes(new_doc,k, [i for i in old_s if v in i ][0][v])elif "table" == k:html_table_to_docx(new_doc,v)else:style = [i for i in old_s if i["style"]["sn"]==k ]style_ws = [i for i in old_ws if i["style"]["sn"]==k ]clone_paragraph(style[0], v, new_doc, style_ws[0])new_doc.save(new_doc_path)# 使用示例
if __name__ == "__main__":body_ws, _ = get_para_style('demo_template.docx')body_s, body_p = get_para_style("1.docx")# 将body_p 或者是压缩后的内容 给llm 如果希望llm 只是参考模版样式,可以压缩如果需要内容或者修改不可压缩# 而后得到json  1.json 进行word生成with open("1.json", "r", encoding="utf-8") as f:body_p=json.loads(f.read())print("获取样式完成",body_p)clone_document(body_s, body_p, body_ws, 'cloned_example.docx')
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH# 创建一个新的Word文档
doc = Document()
for align in [WD_ALIGN_PARAGRAPH.LEFT, WD_ALIGN_PARAGRAPH.RIGHT, WD_ALIGN_PARAGRAPH.CENTER, None]:for blod_flag in [True, False]:# 获取所有可用的段落样式名(只保留段落样式)paragraph_styles = [style for style in doc.styles if style.type == 1  # type == 1 表示段落样式]# 输出样式数量print(f"共找到 {len(paragraph_styles)} 种段落样式:")for style in paragraph_styles:print(f"- {style.name}")# 在文档中添加每个样式对应的段落for style in paragraph_styles:heading = doc.add_paragraph()run = heading.add_run(f"样式名称: {style.name}")run.bold = blod_flagpara = doc.add_paragraph(f"这是一个应用了 '{style.name}' 样式的段落示例。", style=style)para.alignment = align# 添加分隔线(可选)doc.add_paragraph("-" * 40)# 保存为 demo_template.docx
doc.save("demo_template.docx")
print("\n✅ 已生成包含所有段落样式的模板文件:demo_template.docx")

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.pswp.cn/pingmian/83971.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【MATLAB代码】基于MCC(最大相关熵)的EKF,一维滤波,用于解决观测噪声的异常|附完整代码,订阅专栏后可直接查看

本文所述的代码实现了一种基于最大相关熵准则(Maximum Correntropy Criterion, MCC)的鲁棒性卡尔曼滤波算法(MCC-KF),重点解决传统卡尔曼滤波在观测噪声存在异常值时估计精度下降的问题。通过引入高斯核函数对残差进行加权处理,有效降低了异常观测值对状态估计的干扰。订…

46、web实验-遍历数据与页面bug修改

46、web实验-遍历数据与页面bug修改 在Web开发中&#xff0c;遍历数据和修改页面bug是常见的任务。以下是关于这两个主题的讲解&#xff1a; ### 一、遍历数据 **目的**&#xff1a;在页面上动态展示数据&#xff0c;例如用户列表、商品信息等。 **常用方法**&#xff1a; ####…

华为云Flexus+DeepSeek征文|体验华为云ModelArts快速搭建Dify-LLM应用开发平台并创建自己的自定义聊天助手

华为云FlexusDeepSeek征文&#xff5c;体验华为云ModelArts快速搭建Dify-LLM应用开发平台并创建自己的自定义聊天助手 什么是华为云ModelArts 华为云ModelArts ModelArts是华为云提供的全流程AI开发平台&#xff0c;覆盖从数据准备到模型部署的全生命周期管理&#xff0c;帮助…

Qwen大语言模型里,<CLS>属于特殊的标记:Classification Token

Qwen大语言模型里,<CLS>属于特殊的标记:Classification Token 目录 Qwen大语言模型里,<CLS>属于特殊的标记:Classification Token功能解析工作机制应用场景举例说明技术要点在自然语言处理(NLP)领域 都是<CLS> + <SEP>吗?一、CLS和SEP的作用与常见用法1. **CLS标…

R语言AI模型部署方案:精准离线运行详解

R语言AI模型部署方案:精准离线运行详解 一、项目概述 本文将构建一个完整的R语言AI部署解决方案,实现鸢尾花分类模型的训练、保存、离线部署和预测功能。核心特点: 100%离线运行能力自包含环境依赖生产级错误处理跨平台兼容性模型版本管理# 文件结构说明 Iris_AI_Deployme…

JAVA毕业设计224—基于Java+Springboot+vue的家政服务系统(源代码+数据库)

毕设所有选题&#xff1a; https://blog.csdn.net/2303_76227485/article/details/131104075 基于JavaSpringbootvue的家政服务系统(源代码数据库)224 一、系统介绍 本项目前后端分离&#xff0c;分为用户、家政人员、管理员三种角色 1、用户&#xff1a; 登录、注册、轮播…

滴滴 服务端 面经

一、缓存与数据库的使用场景及性能差异 1. 缓存的适用场景 高频读、低频写场景&#xff1a;如商品详情页、用户信息等读多写少的数据&#xff0c;减少数据库压力。实时性要求不高的数据&#xff1a;如首页推荐列表、统计数据&#xff08;非实时更新&#xff09;&#xff0c;允…

linux操作系统---网络协议

目录 案例演练----网络搭建 路由启配置 多个路由情况下如何联通 静态路由 案例演练----网络搭建 Cisco交换机的命令行用户模式1 switch> 特权模式1 switch>enable disable回到用户模式 2 switch#全局配置模式1 switch#config terminal 2 switch(co…

华为OD机试_2025 B卷_计算某个字符出现次数(Python,100分)(附详细解题思路)

文章目录 题目描述字符计数解析&#xff1a;简单高效的统计方法核心解题思路完整代码实现应用场景扩展 题目描述 写出一个程序&#xff0c;接受一个由字母、数字和空格组成的字符串&#xff0c;和一个字符&#xff0c;然后输出"输入字符串&#xff08;第二行输入的字符&a…

华为仓颉语言初识:并发编程之同步机制(上)

前言 线程同步机制是多线程下解决线程对共享资源竞争的主要方式&#xff0c;华为仓颉语言提供了三种常见的同步机制用来保证线程同步安全&#xff0c;分别是原子操作&#xff0c;互斥锁和条件变量。本篇文章详细介绍主要仓颉语言解决同步机制的方法&#xff0c;建议点赞收藏&a…

树莓派远程登陆RealVNC Viewer出现卡顿

原因是&#xff1a;没有连接显示屏&#xff0c;图像传输会受到限制。 没有显示屏怎么解决&#xff1a; &#x1f4dd; 树莓派5虚拟显示器配置教程&#xff08;强制启用全性能GPU渲染&#xff09; &#x1f527; 步骤1&#xff1a;安装虚拟显示驱动 bash 复制 下载 # 更…

go-zero微服务入门案例

一、go-zero微服务环境安装 1、go-zero脚手架的安装 go install github.com/zeromicro/go-zero/tools/goctllatest2、etcd的安装下载地址根据自己电脑操作系统下载对应的版本&#xff0c;具体的使用自己查阅文章 二、创建一个user-rpc服务 1、定义user.proto文件 syntax &qu…

[BIOS]VSCode zx-6000 编译问题

前提&#xff1a;Python 3.6.6及以上版本安装成功&#xff0c;Python 3.6.6路径加到了环境变量# DEVITS工具包准备好 问题&#xff1a;添加环境变量 1&#xff1a;出现环境变量错误&#xff0c;“py -3” is not installed or added to environment variables #先在C:\Windows里…

【Linux】系统部分——进程控制

11.进程控制 文章目录 11.进程控制一、进程创建二、进程终止退出码进程终止的方式 三、进程等待进程等待的方式获取⼦进程status小程序阻塞与非阻塞等待 四、进程程序替换替换原理进程程序替换的接口——exec替换函数 五、总结 一、进程创建 之前学习了fork()函数创建子进程&a…

【读论文】U-Net: Convolutional Networks for Biomedical Image Segmentation 卷积神经网络

摘要1 Introduction2 Network Architecture3 Training3.1 Data Augmentation 4 Experiments5 Conclusion背景知识卷积激活函数池化上采样、上池化、反卷积softmax 归一化函数交叉熵损失 Olaf Ronneberger, Philipp Fischer, Thomas Brox Paper&#xff1a;https://arxiv.org/ab…

蓝牙音乐(A2DP)音频延迟的一些感想跟分析,让你对A2DP体验更佳深入

零.声明 最近做蓝牙协议栈的过程中遇到一些客户偶尔提报音频延迟的问题&#xff0c;所以引发了一些感想&#xff0c;跟大家分享下&#xff0c;音频延迟主要的影响范围是对一些要求实时性比较高的场景有比较差的体验 连接蓝牙看视频的过程中&#xff0c;发现音画不同步&#x…

MySQL 8.0 绿色版安装和配置过程

MySQL作为云计算时代&#xff0c;被广泛使用的一款数据库&#xff0c;他的安装方式有很多种&#xff0c;有yum安装、rpm安装、二进制文件安装&#xff0c;当然也有本文提到的绿色版安装&#xff0c;因绿色版与系统无关&#xff0c;且可快速复制生成&#xff0c;具有较强的优势。…

AGV|无人叉车工业语音播报器|预警提示器LBE-LEX系列性能与接线说明

LBE-LEX系列AGV|无人叉车工业语音播报器|预警提示器&#xff0c;涵盖LBE-LEI-M-00、LBE-LESM-00、LBE-LES-M-01、LBE-LEC-M-00、LBE-KEI-M-00、LBE-KES-M-00、LBE-KES-M-01、LBE-KEC-M-00等型号&#xff0c;适用于各种需要语音提示的场景&#xff0c;主要有AGV、AMR机器人、无人…

行为型设计模式之Interpreter(解释器)

行为型设计模式之Interpreter&#xff08;解释器&#xff09; 前言&#xff1a; 自己的话理解&#xff1a;自定义一个解释器用来校验参数或数据是否合法。 1&#xff09;意图 给定一个语言&#xff0c;定义它的文法的一种表示&#xff0c;并定义一个解释器&#xff0c;这个解…

C++常用的企业级日志库

黄老师跟大家推荐几款在企业开发中最受欢迎的C++日志库! 1. spdlog spdlog 是一个非常流行的开源C++日志库,以其高性能和易用性著称。它支持多线程、异步日志记录以及多种格式化选项。 安装 可以通过包管理器安装,例如 vcpkg: vcpkg install spdlog示例代码 #include…