|
在以前的视频《如何在 Word 中批量制作自己需要的 Anki 挖空卡片?》中曾经介绍过利用 Word 文档文本突出显示的功能批量制作 Anki 挖空卡片。但其中有 3 个比较麻烦的地方:
- 需要手工将突出显示的文本全部替换成带有 Anki 挖空标志的内容;
- 需要手工将完成替换的文档另存为 UTF-8 格式的文本文件;
- 生成的每个挖空卡片如果有多个挖空内容,会同时显示。
现在,我通过编程的方式将上述问题解决。只要电脑里有一份包含突出显示文本的Word文档,然后运行如下Python代码(需将第69行中的Word文档名 D:/demo.docx 进行相应的修改),就能自动生成一个同名文本文件,把它导入到Anki中,就能批量生成每次只显示一个挖空的卡片:
import os
import tempfile
from win32com.client import Dispatch
def change_extension(filename, in_extension, out_extension):
temp = os.path.splitext(filename)
if temp[1] == in_extension:
return temp[0] + out_extension
else:
return "C:/myclozes.txt"
def c1_cn(text, c1="{{c1::"):
c1_count = text.count(c1)
if c1_count > 1:
cn = tuple(x + 1 for x in range(c1_count))
c1format = text.replace(c1, "{{c%d::")
return c1format % cn
else:
return text
def docx_replace(docx_file):
try:
wd = Dispatch("Word.Application")
doc = wd.Documents.Open(docx_file)
wd.visible = False
wd.DisplayAlerts = False
s = wd.Selection
s.Find.ClearFormatting
s.Find.Highlight = True
s.Find.Replacement.ClearFormatting
Changed = s.Find.Execute(
"", False, False, False, False, False, True, 1, True, "{{c1::^&}}", 2
)
if Changed:
doctext = doc.Range(
0,
).text
with tempfile.NamedTemporaryFile("w", encoding="utf-8", delete=False) as fp:
fp.write(doctext)
temptextfile = fp.name
else:
temptextfile = ""
doc.Close(0)
wd.Quit()
except:
temptextfile = ""
print("文件:%s 错误或不存在!" % docx_file)
return temptextfile
def c1file_cnfile(c1filename, cnfilename):
try:
file1 = open(c1filename, "r", encoding="utf-8")
filen = open(cnfilename, "w", encoding="utf-8")
while True:
Oneline = file1.readline()
if len(Oneline) != 0:
if Oneline.count("{{c1::") != 0:
filen.write(c1_cn(Oneline))
else:
break
return True
except:
return False
finally:
filen.close
file1.close
def main():
HighlightDocx = "D:/demo.docx"
cntxt_file = change_extension(HighlightDocx, ".docx", ".txt")
clozetempfile = docx_replace(HighlightDocx)
if clozetempfile == "":
print("没有找到挖空内容!")
else:
if c1file_cnfile(clozetempfile, cntxt_file):
os.remove(clozetempfile)
print("生成的挖空文件保存为:" + cntxt_file)
if __name__ == "__main__":
main()
上述代码在Win10系统中,用Thonny运行通过(关于该软件,请看《入门Python就用这款代码编辑器》的介绍)。由于代码中用到了第三方库win32com,因此还需要通过Thonny的菜单“管理包”安装一下。
经过测试,如果电脑上没有安装 Ms Word,而是安装了 WPS,代码也能正常执行。代码生成的文本文件要导入 Anki,方法与视频《如何在 Word 中批量制作自己需要的 Anki 挖空卡片?》介绍的完全相同。 |
|