如何使用pyspellchecker批量替换XML中OCR识别的法语拼写错误
现有代码的核心问题
- 直接删除了所有XML标签,丢失了原始TEI文件结构,输出结果不再是可用的XML
- 分词逻辑错误:用
split(' ')按两个空格拆分文本,无法正确拆分所有独立词汇,导致拼写检查模块无法识别到错误词 - 拼写修正逻辑错误:
correct = spell.correction(word)中word是未定义变量,没有遍历所有错误单词生成对应修正映射;后续将所有错误词拼接为长字符串替换,完全无法匹配到文本中的单个错误词 - 文件读写逻辑混乱:用
r+模式写入会在文件末尾追加内容,而非逐词替换原内容
可直接运行的修正方案
这里提供保留原始XML结构的版本,仅修正标签内的文本内容,不破坏TEI格式:
import re from spellchecker import SpellChecker entry = "test.xml" output = "test_out.xml" # 初始化法语拼写检查器 spell = SpellChecker(language='fr') # 专有名词白名单,避免拼写检查误判(可根据需求补充) white_list = {"Confucius", "Y-king", "Chu-king", "Chi-king", "Ssée-chu", "Tchun-tfiou", "Lild", "Fo-hi", "Vifdeîau", "Chufcing"} # 读取原始XML内容 with open(entry, 'r', encoding='utf-8') as f: raw_content = f.read() # 匹配XML标签外的纯文本内容进行修正 def correct_text(match): text = match.group(0) # 拆分所有独立词汇,保留标点和空格格式 words = re.findall(r"([a-zA-ZÀ-ÿ'-]+|\s+|[^\w\s])", text) corrected_words = [] for word in words: stripped_word = word.strip().lower() # 跳过空格、标点、白名单内的专有名词 if not stripped_word or not stripped_word.isalpha() or stripped_word in white_list: corrected_words.append(word) continue # 检查拼写并修正,保留原单词的大小写格式 if spell.unknown([stripped_word]): corrected = spell.correction(stripped_word) if word.istitle(): corrected = corrected.capitalize() elif word.isupper(): corrected = corrected.upper() corrected_words.append(corrected) else: corrected_words.append(word) return ''.join(corrected_words) # 只替换XML标签外的文本,保留所有标签结构 processed_content = re.sub(r'(?<=>)[^<]+(?=<)', correct_text, raw_content) # 写入修正后的XML with open(output, 'w', encoding='utf-8') as f: f.write(processed_content)
注意事项
- 法语拼写检查器对古法语、专有名词的识别准确率有限,建议根据文件内容补充白名单,避免误修正
- 若不需要保留XML结构,仅需要修正后的纯文本,删除正则匹配标签的逻辑,直接对全文本分词修正即可
内容的提问来源于stack exchange,提问作者ljushu
相关产品推荐
相关产品推荐

