三省堂 クラウン独和辞典 第5版 mdx

用pyglossary将.mdx转换成.txt,用下述python脚本修改txt,用pangloss将.txt转换回.mdx。

import re
import sys
from bs4 import BeautifulSoup

def extract_display_headword(html_content):
    """
    从 <span class="hw_midasigo"> 中提取纯文本显示词头
    去除所有 HTML 标签、图片、分隔符标记
    """
    soup = BeautifulSoup(html_content, 'html.parser')
    # 查找第一个 class 包含 'hw_midasigo' 的 span
    hw_tag = soup.find('span', class_=re.compile(r'^hw_midasigo'))
    if not hw_tag:
        return None
    # 获取纯文本(自动递归处理嵌套标签)
    text = hw_tag.get_text(strip=True)
    # 移除所有方括号及其内容(半角和全角)
    text = re.sub(r'[\[[][^\]]*?[\]]]', '', text)
    # 移除结尾的空白和数字(可能单独存在的序号)
    text = re.sub(r'\d+$', '', text)
    text = re.sub(r'\s+$', '', text)
    # 移除常见的分隔符(点、竖线、中黑点等)
    text = re.sub(r'[|・·•*=()]', '', text)
    # 去除多余空白
    text = ' '.join(text.split())
    return text if text else None

def process_line(line):
    """
    处理一行 TSV,返回修正后的行
    如果无法处理,返回原行
    """
    line = line.rstrip('\n')
    if '\t' not in line:
        return line
    headword_part, content = line.split('\t', 1)
    
    # 分割词头列表
    headwords = headword_part.split('|')
    
    # 提取显示词头
    display = extract_display_headword(content)
    if not display:
        return line
    
    # 如果显示词头已经在词头列表中(完全匹配),则无需添加
    if display in headwords:
        return line
    
    # 否则,将显示词头添加到最前面
    new_headwords = [display] + headwords
    new_headword_part = '|'.join(new_headwords)
    
    return new_headword_part + '\t' + content

def main(input_file, output_file):
    with open(input_file, 'r', encoding='utf-8') as fin:
        lines = fin.readlines()
    
    processed_lines = []
    total = len(lines)
    modified = 0
    for i, line in enumerate(lines, 1):
        new_line = process_line(line)
        if new_line != line.rstrip('\n'):
            modified += 1
            print(f'已修正第 {i} 行')
        processed_lines.append(new_line)
    
    with open(output_file, 'w', encoding='utf-8') as fout:
        fout.write('\n'.join(processed_lines))
    
    print(f'\n处理完成!共处理 {total} 行,修正 {modified} 个词条。')
    print(f'输出文件:{output_file}')

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print('用法: python fix_headwords.py 输入文件.txt 输出文件.txt')
        sys.exit(1)
    main(sys.argv[1], sys.argv[2])

CROWNDJ5.mdx (13.2 MB)