python颜色填充代码_求懂WORD的大佬怎么一次性填充颜色或者使用python识别

[Python] 纯文本查看 复制代码# -*- coding: utf-8 -*-

import os

import docx

from docx.oxml.ns import qn

from docx.shared import RGBColor

from docx.shared import Pt

# input_filename = input("请输入需要去除重复的文件绝对路径:\n示例:G:\scala\scala_test\my_test\data\pc.txt")

cwd = os.getcwd()

input_file = os.path.join(cwd, "input.txt")

output_file = os.path.join(cwd, "output.docx")

while True:

input_filename = input("请输入需要调整格式txt文件绝对路径:\n默认为当前目录:" + input_file + "\n")

output_filename = input("请输入调整后txt文件保存的绝对路径:\n默认为当前目录:" + output_file +

"\n")

if len(input_filename) == 0:

input_filename = input_file

if len(output_filename) == 0:

output_filename = output_file

if os.path.isfile(input_filename):

break

else:

print("路径输入错误,请重新输入!")

continue

rgbs = {

"黑色": (0, 0, 0),

"红色": (255, 0, 0),

"蓝色": (0, 0, 255),

"黄色": (255, 255, 0),

"青色": (0, 255, 255),

"品红": (0, 255, 255),

"CornflowerBlue": (100, 149, 237)

}

try:

print("请选择题目颜色...键入示例:黑色")

filr = 1

for rgb in rgbs.keys():

print(str(filr) + "." + rgb)

filr += 1

key_rgb = RGBColor(*rgbs[input()])

print("请选择答案颜色...")

filr = 1

for rgb in rgbs.keys():

print(str(filr) + "." + rgb)

filr += 1

value_rgb = RGBColor(*rgbs[input()])

except:

# key_rgb = RGBColor(0, 0, 0)

# value_rgb = RGBColor(70, 130, 180)

key_rgb = RGBColor(100, 149, 237)

value_rgb = RGBColor(255, 0, 0)

print("使用默认颜色...")

document = docx.Document()

document.add_heading('单选题', 0) # 插入标题

document.styles['Normal'].font.name = '宋体' # 设置字体

document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')

values = list()

key = ""

flag = False

def insert_docx(key_rgb, value_rgb, key, values):

p = document.add_paragraph() # 插入段落

key_run = p.add_run(key)

key_run.font.color.rgb = key_rgb

key_run.font.size = Pt(12)

# 加粗

key_run.font.bold = True

run = p.add_run(values)

# 字体颜色

run.font.color.rgb = value_rgb

with open(input_filename, encoding="utf-8") as f:

lines = f.readlines()

for line in lines:

if len(line) < 6:

num_s = line.strip().split("、")

else:

num_s = line[0:6].split("、")

try:

if len(num_s) >= 2 and num_s[0].isdigit():

if flag:

insert_docx(key_rgb, value_rgb, key, values)

flag = False

values = list()

key = line # .replace(num_s[0] + ".", "")

else:

values.append(line)

flag = True

except Exception as e:

print(e, line)

values = list()

key = ""

flag = False

document.save(output_filename) # 保存文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值