如何基于指定语言的Microsoft Office词典实现程序化拼写检查
问题
- 需求:通过程序化方式,使用指定语言的Microsoft Office词典对单词列表进行拼写检查。
- 当前实现:使用Python的
win32com.client调用Word Application API,可正常获取对应语言ID的词典对象,但调用CheckSpelling或GetSpellingSuggestions方法时,始终仅使用Word默认语言的词典,无法切换至指定语言。 - 已尝试操作:设置临时文档Range的
LanguageID、修改文档样式的LanguageID,均无效果。 - 限制条件:仅可使用Microsoft Office自带词典,不考虑其他拼写检查库,暂不采用将单词批量写入临时文档再提取结果的方案。
附相关代码
原拼写检查代码:
import os import win32com.client #hard-coded parameters input_file = "test_in.txt" output_file = "test_out.txt" language_id = 1031 #1033 en-us/1029 cz/1031 de/1034 es/1036 fr/1040 it/1051 sk if not os.path.exists(input_file): print("Input file does not exist.") os._exit(-1) #instantiating Word application word_app = win32com.client.Dispatch("Word.Application") #looking up the dictionary object for the language_id, no error control here dictionary_object = None languages = word_app.Languages for language in languages: if language.ID == language_id: act_dict_obj = language.ActiveSpellingDictionary if act_dict_obj: dictionary_object = act_dict_obj break print( "langID: " + str(language_id) ) print( "dict: " + str(dictionary_object) ) dictionary_path = dictionary_object.Path + word_app.PathSeparator + dictionary_object.Name print( "dictPath: " + dictionary_path ) #GetSpellingSuggestions works only with any document opened temp_doc = word_app.Documents.Add() range = temp_doc.Range( 0, 0 ) range.text = "Bla bla bla" range.LanguageID = language_id with open(input_file, 'r', encoding='utf-8') as input_fp: words = input_fp.read().split() with open(output_file, 'w', encoding='utf-8') as output_fp: for word in words: #either bool check (two top lines) or suggestion list (two bottom lines) #is_good = word_app.CheckSpelling(word,"","",dict ) #output_fp.write( word + " " + str(is_good ) + "\n" ) results = word_app.GetSpellingSuggestions(word,"","",dictionary_object ) output_fp.write( word + ": " + ", ".join( map( lambda sugg: str(sugg), results ) ) + "\n" ) #clean up temp_doc.Close(False) word_app.Quit()
尝试修改文档语言的代码片段:
temp_doc.Activate() temp_doc.Styles(-66).LanguageID = language_id temp_doc.Styles(-1).LanguageID = language_id temp_doc.Content.Style=-1 temp_doc.Content.text = "This is empty text." temp_doc.Content.LanguageID = language_id doclang = temp_doc.Content.LanguageID print( "detected lang: " + str(doclang ) )
解决方案
问题核心:直接调用word_app.CheckSpelling或word_app.GetSpellingSuggestions时,Word会优先使用应用级默认语言设置,而非你指定的词典对象。正确做法是通过绑定了目标语言的Range对象调用拼写检查方法,让Word基于Range的语言配置选择对应词典。
修改后完整代码
import os import win32com.client # 硬编码参数 input_file = "test_in.txt" output_file = "test_out.txt" language_id = 1031 # 1033 en-us/1029 cz/1031 de/1034 es/1036 fr/1040 it/1051 sk if not os.path.exists(input_file): print("输入文件不存在。") os._exit(-1) # 启动Word应用,设置为后台运行避免弹窗 word_app = win32com.client.Dispatch("Word.Application") word_app.Visible = False # 验证目标语言词典是否存在(非必需,仅作状态确认) dictionary_object = None languages = word_app.Languages for language in languages: if language.ID == language_id: act_dict_obj = language.ActiveSpellingDictionary if act_dict_obj: dictionary_object = act_dict_obj break print(f"语言ID: {language_id}") print(f"词典对象: {dictionary_object}") if dictionary_object: dictionary_path = dictionary_object.Path + word_app.PathSeparator + dictionary_object.Name print(f"词典路径: {dictionary_path}") # 创建临时文档并配置拼写检查用的Range temp_doc = word_app.Documents.Add() check_range = temp_doc.Range(0, 0) # 绑定目标语言ID到Range check_range.LanguageID = language_id # 读取待检查单词 with open(input_file, 'r', encoding='utf-8') as input_fp: words = input_fp.read().split() # 执行拼写检查并输出结果 with open(output_file, 'w', encoding='utf-8') as output_fp: for word in words: # 将待检查单词写入Range check_range.Text = word # 使用Range的CheckSpelling方法验证拼写 is_correct = check_range.CheckSpelling() # 如需获取拼写建议,替换为以下代码: # suggestions = check_range.GetSpellingSuggestions() # suggestion_list = [str(sugg) for sugg in suggestions] if suggestions else [] output_fp.write(f"{word} {str(is_correct)}\n") # 若用建议则输出:output_fp.write(f"{word}: {', '.join(suggestion_list)}\n") # 清理资源 temp_doc.Close(SaveChanges=False) word_app.Quit()
关键说明
- 必须使用Range对象的拼写方法:Range的
LanguageID配置会直接决定Word调用对应语言的激活词典,而非依赖应用级默认设置。 - 后台运行Word:设置
word_app.Visible = False可避免Word窗口弹出,提升运行效率。 - 无需手动传入词典对象:只要Range的语言ID设置正确,Word会自动匹配对应语言的词典,无需额外传递词典参数。
内容的提问来源于stack exchange,提问作者Jindroush
相关产品推荐
相关产品推荐

