如何使用Python将带格式的文本写入剪贴板并在粘贴时保留格式?
Windows下用Python向剪贴板写入带加粗格式内容的方案
方案1:写入HTML格式富文本
适用于需要通用富文本格式的场景,粘贴到Word、聊天框、网页编辑器等支持富文本的位置时会自动保留格式,粘贴到纯文本编辑器时自动降级为普通文本。
- 先安装依赖:
pip install pywin32 - 使用以下代码实现:
import win32clipboard def copy_rich_text_to_clipboard(rich_content): # Windows剪贴板HTML格式标准头模板 html_template = """Version:0.9 StartHTML:0000000000 EndHTML:0000000000 StartFragment:0000000000 EndFragment:0000000000 <html> <body> <!--StartFragment--> {} <!--EndFragment--> </body> </html> """ # 拼接完整HTML内容 full_html = html_template.format(rich_content) # 计算各节点偏移量 start_html = full_html.find('<html>') end_html = len(full_html) start_frag = full_html.find('<!--StartFragment-->') + len('<!--StartFragment-->') end_frag = full_html.find('<!--EndFragment-->') # 替换模板中的占位偏移量 full_html = full_html.replace('StartHTML:0000000000', f'StartHTML:{start_html:010d}') full_html = full_html.replace('EndHTML:0000000000', f'EndHTML:{end_html:010d}') full_html = full_html.replace('StartFragment:0000000000', f'StartFragment:{start_frag:010d}') full_html = full_html.replace('EndFragment:0000000000', f'EndFragment:{end_frag:010d}') # 写入剪贴板 win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() # 注册HTML格式标识 cf_html = win32clipboard.RegisterClipboardFormat("HTML Format") win32clipboard.SetClipboardData(cf_html, full_html.encode('utf-8')) # 同时写入纯文本版本兼容纯文本场景 win32clipboard.SetClipboardText(rich_content.replace('<b>','').replace('</b>','')) win32clipboard.CloseClipboard() # 调用示例:传入带<b>标签的加粗内容 copy_rich_text_to_clipboard("<b>Hello World!</b>")
方案2:使用Unicode粗体字符
你示例中展示的粗体字符属于Unicode数学符号字符集,本质是特殊纯文本字符,无需依赖富文本支持,在所有场景下都能显示为粗体效果,实现更简单。
- 先安装依赖:
pip install pyperclip - 直接复制对应粗体字符即可:
import pyperclip pyperclip.copy("𝗵𝗲𝗹𝗹𝗼 𝘄𝗼𝗿𝗹𝗱")
内容的提问来源于stack exchange,提问作者cool movies
相关产品推荐
相关产品推荐

