[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) # 保存文档