import os, pythoncom, win32com.client as win32
# ---------------------- 工具函数 ----------------------
def get_or_add_style(doc, name):
try:
return doc.Styles(name)
except:
return doc.Styles.Add(Name=name, Type=1) # 1=段落样式
# ---------------------- 主程序 ----------------------
pythoncom.CoInitialize()
try:
app = win32.Dispatch("Word.Application")
except:
app = win32.Dispatch("Kwps.Application")
app.Visible = True
doc = app.Documents.Add()
# Word 常数
wdCollapseEnd = 0
wdStory = 6
wdWord9TableBehavior = 1
wdAutoFitContent = 1
wdFormatDocumentDefault = 12
# ---------- 1. 建立基础样式(匹配附件模板格式) ----------
def make_styles():
# 题型标题(【单选题】等)
s = get_or_add_style(doc, "题型标题")
s.Font.NameFarEast = s.Font.Name = "黑体"
s.Font.Size = 12
s.Font.Bold = True
pf = s.ParagraphFormat
pf.SpaceBefore = 6
pf.SpaceAfter = 3
pf.Alignment = 0
# 题干/选项/解析文本样式
s = get_or_add_style(doc, "题目内容")
s.Font.NameFarEast = s.Font.Name = "宋体"
s.Font.Size = 10.5
pf = s.ParagraphFormat
pf.FirstLineIndent = 0
pf.LineSpacingRule = 3
pf.LineSpacing = 1.25
pf.Alignment = 0
# 选项专属样式(保持缩进一致性)
s = get_or_add_style(doc, "选项")
s.Font.NameFarEast = s.Font.Name = "宋体"
s.Font.Size = 10.5
pf = s.ParagraphFormat
pf.FirstLineIndent = 0
pf.LineSpacingRule = 3
pf.LineSpacing = 1.25
pf.Alignment = 0
# 备注信息样式(所属章、难度等)
s = get_or_add_style(doc, "备注")
s.Font.NameFarEast = s.Font.Name = "宋体"
s.Font.Size = 10.5
pf = s.ParagraphFormat
pf.SpaceBefore = 3
pf.SpaceAfter = 6
pf.Alignment = 0
make_styles()
# ---------- 2. 辅助函数:批量写入题目 ----------
rng = doc.Range()
rng.Collapse(wdCollapseEnd)
def write_style(style, text, newline=True):
"""按指定样式写入文本"""
rng.Style = style
rng.Text = text
if newline:
rng.InsertParagraphAfter()
rng.Collapse(wdCollapseEnd)
def add_single_choice(no, score, question, opt_a, opt_b, opt_c, opt_d, correct, chapter, difficulty, analysis="", knowledge=""):
"""添加单选题"""
write_style(doc.Styles("题型标题"), f"【单选题】({score}分)")
write_style(doc.Styles("题目内容"), f"{no}. {question}({correct})")
write_style(doc.Styles("选项"), f"A、{opt_a}")
write_style(doc.Styles("选项"), f"B、{opt_b}")
write_style(doc.Styles("选项"), f"C、{opt_c}")
write_style(doc.Styles("选项"), f"D、{opt_d}")
write_style(doc.Styles("备注"), f"所属章:{chapter}")
write_style(doc.Styles("备注"), f"难度:{difficulty}")
if analysis:
write_style(doc.Styles("备注"), f"解析:{analysis}")
if knowledge:
write_style(doc.Styles("备注"), f"知识点:{knowledge}")
rng.InsertParagraphAfter()
def add_multi_choice(no, score, question, opt_a, opt_b, opt_c, opt_d, correct, chapter, difficulty, analysis="", knowledge=""):
"""添加多选题"""
write_style(doc.Styles("题型标题"), f"【多选题】({score}分)")
write_style(doc.Styles("题目内容"), f"{no}. {question}({correct})")
write_style(doc.Styles("选项"), f"A、{opt_a}")
write_style(doc.Styles("选项"), f"B、{opt_b}")
write_style(doc.Styles("选项"), f"C、{opt_c}")
write_style(doc.Styles("选项"), f"D、{opt_d}")
write_style(doc.Styles("备注"), f"所属章:{chapter}")
write_style(doc.Styles("备注"), f"难度:{difficulty}")
if analysis:
write_style(doc.Styles("备注"), f"解析:{analysis}")
if knowledge:
write_style(doc.Styles("备注"), f"知识点:{knowledge}")
rng.InsertParagraphAfter()
def add_fill_blank(no, score_per, question, case_sensitive, order_sensitive, chapter, difficulty, analysis="", knowledge=""):
"""添加填空题(题干已含真实答案)"""
write_style(doc.Styles("题型标题"), f"【填空题】(每空{score_per}分)")
write_style(doc.Styles("题目内容"), f"{no}. {question}")
write_style(doc.Styles("备注"), f"判分时答案内字母区分大小写:{case_sensitive}")
write_style(doc.Styles("备注"), f"判分时区分多个空的先后顺序:{order_sensitive}")
write_style(doc.Styles("备注"), f"所属章:{chapter}")
write_style(doc.Styles("备注"), f"难度:{difficulty}")
if analysis:
write_style(doc.Styles("备注"), f"解析:{analysis}")
if knowledge:
write_style(doc.Styles("备注"), f"知识点:{knowledge}")
rng.InsertParagraphAfter()
def add_judge(no, score, question, correct, chapter, difficulty, analysis="", knowledge=""):
"""添加判断题"""
write_style(doc.Styles("题型标题"), f"【判断题】({score}分)")
write_style(doc.Styles("题目内容"), f"{no}. {question}({correct})")
write_style(doc.Styles("备注"), f"所属章:{chapter}")
write_style(doc.Styles("备注"), f"难度:{difficulty}")
if analysis:
write_style(doc.Styles("备注"), f"解析:{analysis}")
if knowledge:
write_style(doc.Styles("备注"), f"知识点:{knowledge}")
rng.InsertParagraphAfter()
# ---------- 3. 第6章 题库内容(字符串操作与正则表达式) ----------
chapter = "第6章 字符串操作与正则表达式"
# 一、单选题(6道,覆盖全章节知识点)
add_single_choice(
no=1,
score=2,
question="Python中执行'hello world'.split(' '),返回的结果是",
opt_a="['hello', 'world']",
opt_b="('hello', 'world')",
opt_c="{'hello': 'world'}",
opt_d="hello world",
correct="A",
chapter=chapter,
difficulty="简单",
analysis="split()是字符串常用分割方法,以指定字符为分隔符,返回包含分割后子串的列表;本题以空格分割,返回['hello', 'world']",
knowledge="字符串常用操作(split()方法)"
)
add_single_choice(
no=2,
score=2,
question="以下哪种是Python 3.6+新增的字符串格式化方式",
opt_a="%格式化(如'name: %s' % 'Tom')",
opt_b="str.format()(如'name: {}'.format('Tom'))",
opt_c="f-string(如f'name: {name}')",
opt_d="字符串拼接(如'name: ' + 'Tom')",
correct="C",
chapter=chapter,
difficulty="简单",
analysis="%格式化和str.format()是早期格式化方式,f-string是Python 3.6+新增,支持嵌入变量和表达式,语法更简洁",
knowledge="字符串格式化方法(f-string)"
)
add_single_choice(
no=3,
score=3,
question="正则表达式中,元字符'^'的作用是",
opt_a="匹配任意单个字符",
opt_b="匹配字符串的开头位置",
opt_c="匹配字符串的结尾位置",
opt_d="匹配前面的字符0次或多次",
correct="B",
chapter=chapter,
difficulty="一般",
analysis="正则元字符中,'^'匹配字符串开头,'$'匹配结尾,'.'匹配任意单个字符,'*'匹配前面字符0次或多次",
knowledge="正则表达式(基础元字符)"
)
add_single_choice(
no=4,
score=3,
question="Python中使用re模块匹配字符串时,若要返回所有匹配的结果,应使用哪个函数",
opt_a="re.match()",
opt_b="re.search()",
opt_c="re.findall()",
opt_d="re.sub()",
correct="C",
chapter=chapter,
difficulty="一般",
analysis="re.match()匹配字符串开头,re.search()匹配首个符合规则的子串,re.findall()返回所有匹配结果列表,re.sub()用于替换匹配内容",
knowledge="正则表达式(re模块函数)"
)
add_single_choice(
no=5,
score=4,
question="执行'python is easy'.replace('easy', 'powerful'),返回的结果是",
opt_a="python is powerful",
opt_b="python is easy",
opt_c="['python', 'is', 'powerful']",
opt_d="报错(字符串不可变)",
correct="A",
chapter=chapter,
difficulty="一般",
analysis="字符串是不可变对象,但replace()方法会创建并返回包含替换结果的新字符串,原字符串不变,本题将'easy'替换为'powerful',结果为'python is powerful'",
knowledge="字符串常用操作(replace()方法)"
)
add_single_choice(
no=6,
score=4,
question="正则表达式r'\\d{3}-\\d{4}'可匹配以下哪种格式的字符串",
opt_a="1234567",
opt_b="123-4567",
opt_c="abc-defg",
opt_d="12-3456",
correct="B",
chapter=chapter,
difficulty="困难",
analysis="\\d匹配数字,{n}匹配前面元素n次;r'\\d{3}-\\d{4}'表示匹配3个数字+'-'+4个数字,对应格式为'123-4567'",
knowledge="正则表达式(量词与转义字符)"
)
# 二、多选题(4道,侧重知识点区分与应用)
add_multi_choice(
no=1,
score=4,
question="以下属于Python字符串常用操作的有",
opt_a="strip():去除字符串两端空白字符",
opt_b="upper():将字符串转换为大写",
opt_c="join():将列表元素拼接为字符串",
opt_d="append():向字符串末尾添加字符",
correct="ABC",
chapter=chapter,
difficulty="简单",
analysis="append()是列表的添加方法,字符串无此方法;strip()去空白、upper()转大写、join()拼接列表均为字符串常用操作",
knowledge="字符串常用操作(strip()/upper()/join())"
)
add_multi_choice(
no=2,
score=4,
question="以下关于字符串格式化方法的描述正确的有",
opt_a="%格式化支持整数(%d)、字符串(%s)等多种格式符",
opt_b="str.format()可通过位置参数({})或关键字参数({name})占位",
opt_c="f-string中可直接嵌入Python表达式(如f'{1+2}')",
opt_d="三种格式化方式(%/format/f-string)均支持所有数据类型",
correct="ABC",
chapter=chapter,
difficulty="一般",
analysis="%格式化对部分复杂类型(如字典)支持有限,需手动处理;ABC选项分别是三种格式化方式的核心特性,描述正确",
knowledge="字符串格式化方法(%/format/f-string对比)"
)
add_multi_choice(
no=3,
score=5,
question="正则表达式中,以下哪些元字符具有特殊含义",
opt_a=".",
opt_b="*",
opt_c="?",
opt_d="a",
correct="ABC",
chapter=chapter,
difficulty="一般",
analysis="正则中'.'匹配任意单个字符,'*'匹配0次或多次,'?'匹配0次或1次,均为特殊元字符;'a'是普通字符,仅匹配自身",
knowledge="正则表达式(特殊元字符)"
)
add_multi_choice(
no=4,
score=5,
question="Python中re模块的re.sub()函数参数包括",
opt_a="pattern:正则匹配规则",
opt_b="repl:替换后的内容",
opt_c="string:待处理的原始字符串",
opt_d="count:最大替换次数(可选)",
correct="ABCD",
chapter=chapter,
difficulty="困难",
analysis="re.sub(pattern, repl, string, count=0)的核心参数包括匹配规则、替换内容、原始字符串,count可选(默认0表示全部替换),四个选项均为其参数",
knowledge="正则表达式(re.sub()函数)"
)
# 三、填空题(4道,题干含真实答案,无占位符)
add_fill_blank(
no=1,
score_per=2,
question="Python中执行'abc123'.isdigit()返回【False】,执行'123abc'.isalpha()返回【False】",
case_sensitive="是",
order_sensitive="是",
chapter=chapter,
difficulty="简单",
analysis="isdigit()仅当字符串全为数字时返回True,'abc123'含字母,返回False;isalpha()仅当字符串全为字母时返回True,'123abc'含数字,返回False",
knowledge="字符串常用操作(isdigit()/isalpha()方法)"
)
add_fill_blank(
no=2,
score_per=2,
question="使用str.format()格式化时,若要指定参数位置,可写成【{索引}(如'{0} {1}'.format(a,b))】;使用f-string时,变量需在【花括号({})】中直接嵌入",
case_sensitive="否",
order_sensitive="是",
chapter=chapter,
difficulty="一般",
analysis="str.format()支持{0}、{1}指定参数位置;f-string通过{变量名}直接嵌入变量,如f'age: {age}'",
knowledge="字符串格式化方法(format()/f-string)"
)
add_fill_blank(
no=3,
score_per=3,
question="正则表达式中,【\\D】匹配任意非数字字符,【\\w】匹配任意字母、数字或下划线(即单词字符)",
case_sensitive="是",
order_sensitive="是",
chapter=chapter,
difficulty="一般",
analysis="正则中\\d匹配数字,\\D是\\d的否定(非数字);\\w匹配单词字符([a-zA-Z0-9_]),\\W是其否定",
knowledge="正则表达式(字符类元字符)"
)
add_fill_blank(
no=4,
score_per=3,
question="Python中读取多行字符串可使用【三引号】(如'''内容'''),若要在字符串中保留原始转义字符,需在字符串前加【r(原始字符串)】前缀",
case_sensitive="是",
order_sensitive="是",
chapter=chapter,
difficulty="困难",
analysis="三引号('''或\""")支持多行字符串;原始字符串前缀r可让转义字符(如\\n)不生效,保留原始格式,常用于正则表达式",
knowledge="字符串基础(多行字符串/原始字符串)"
)
# 四、判断题(5道,纠正易混淆知识点)
add_judge(
no=1,
score=2,
question="Python字符串是不可变对象,因此无法通过任何方法修改其内容(对/错)",
correct="错",
chapter=chapter,
difficulty="简单",
analysis="字符串不可变指无法直接修改原有字符,但可通过replace()、join()等方法创建新字符串,间接实现'修改'效果",
knowledge="字符串不可变性与常用操作"
)
add_judge(
no=2,
score=2,
question="f-string的格式化效率高于%格式化和str.format()(对/错)",
correct="对",
chapter=chapter,
difficulty="一般",
analysis="f-string在编译时直接解析变量,无需运行时额外处理,格式化效率显著高于%格式化(字符串拼接)和str.format()(参数匹配)",
knowledge="字符串格式化方法(效率对比)"
)
add_judge(
no=3,
score=2,
question="正则表达式re.match()和re.search()都能匹配字符串任意位置的子串(对/错)",
correct="错",
chapter=chapter,
difficulty="一般",
analysis="re.match()仅匹配字符串开头位置的子串,re.search()匹配字符串任意位置的首个符合规则的子串,二者匹配范围不同",
knowledge="正则表达式(re.match()/re.search()对比)"
)
add_judge(
no=4,
score=3,
question="执行'hello'.center(10, '-')返回'--hello---'(对/错)",
correct="对",
chapter=chapter,
difficulty="一般",
analysis="center(width, fillchar)方法将字符串居中,总长度为width,空白处用fillchar填充;10-5=5个空白,左右各2个'-'和3个'-',结果为'--hello---'",
knowledge="字符串常用操作(center()方法)"
)
add_judge(
no=5,
score=3,
question="正则表达式r'[a-zA-Z0-9]'与r'\\w'匹配的字符范围完全一致(对/错)",
correct="错",
chapter=chapter,
difficulty="困难",
analysis="r'\\w'匹配字母、数字和下划线([a-zA-Z0-9_]),比r'[a-zA-Z0-9]'多了下划线,二者匹配范围不完全一致",
knowledge="正则表达式(字符类与\\w元字符)"
)
# ---------- 4. 保存文档 ----------
save_path = os.path.join(os.path.expanduser("~"), "Desktop", "第6章字符串操作与正则表达式题库.docx")
doc.SaveAs(save_path, FileFormat=wdFormatDocumentDefault)
print(f"第6章题库文档已生成,保存路径:{save_path}")
pythoncom.CoUninitialize()