# 小白如何mdx转excel

**URL:** <https://forum.freemdict.com/t/topic/35290>\
**Category:** 技术交流与词典编修\
**Tags:** python, anki, 技术, ⭐star\
**Created:** [2024 年12 月 27 日 23:20 UTC](https://forum.freemdict.com/t/topic/35290 "2024-12-27T23:20:39Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

作者： ![yium3023](https://forumcdn.freemdict.com/letter_avatar_proxy/v4/letter/y/35a633/32.png) [@yium3023](https://forum.freemdict.com/u/yium3023)\
发布日期： [2024 年12 月 27 日 23:20 UTC](https://forum.freemdict.com/t/topic/35290/1 "2024-12-27T23:20:39Z")

</div>

找到三个教程

> **[Mdx 格式词典文件转换为 Excel 格式术语表\_exe\_mdx\_双语](https://m.sohu.com/a/735227120_121292768/)**
>
> P.S. 如有需要，推荐使用 Glossary Converter，将 xlsx 术语表转为 sdltb 和 tbx 格式术语库2
> 操作限制对更加复杂的词典文件，采用同样方法将提取的中英双语粘贴到 Exce…

> **[Python解析MDX词典数据并保存到Excel\_mdx转excel-CSDN博客](https://blog.csdn.net/as604049322/article/details/132843251)**
>
> 文章浏览阅读1.8k次，点赞2次，收藏8次。下载help.mdx词典后，我们无法直接查看，我们可以使用readmdict库来完成对mdx文件的读取。同时我们可以看到有部分词的描述可能会嵌套列表。\_mdx转excel

> **[搜索引擎：获取并处理mdx英汉词典文件为数据库\_mdx词库-CSDN博客](https://blog.csdn.net/yt266666/article/details/127474784)**
>
> 文章浏览阅读4k次，点赞4次，收藏16次。获取mdx后缀的词典文件后难以使用，利用程序将其转化成本地的数据库，从而快速读取与查询其中的内容。\_mdx词库

一个同站的大佬给了代码

> [@\[已解决\]解析mdx按单个例句+对应释义导出到Excel表格](https://forum.freemdict.com/t/topic/29040):
>
> 各位论坛大佬你们好。 我目前在使用韦氏高阶双解v3词典配合Anki来背单词，我的学习方法是单词的每个例句单独制卡,但是手动复制每个例句以及对应的释义，粘贴到表格再导出到Anki，真的太耗费时间了（如图） 非常希望有大佬能帮助指导下： 整个释义包括例句是在div class="sense"里的 [图片] 但是释义通常都包含多个例句div class=“vi\_conte…

---

<div class="post-metadata">

作者： ![yium3023](https://forumcdn.freemdict.com/letter_avatar_proxy/v4/letter/y/35a633/32.png) [@yium3023](https://forum.freemdict.com/u/yium3023)\
发布日期： [2024 年12 月 31 日 04:04 UTC](https://forum.freemdict.com/t/topic/35290/3 "2024-12-31T04:04:03Z")

</div>

最终选择了cursor，经过两天苦苦挣扎，完成了一半，实现了分出单词，音标部分，以及单词多个词性再列一行， 😭本来想把每个意思也再分一行然后后面加上自己的例句的，算了太累了，我拆的是中阶牛津  
通过网盘分享的文件：中阶单词库.xlsx  
链接: [https://pan.baidu.com/s/12HnedyD3Q8xpcLi5Ak1C\_Q?pwd=7h4g](https://pan.baidu.com/s/12HnedyD3Q8xpcLi5Ak1C_Q?pwd=7h4g) 提取码: 7h4g  
–来自百度网盘超级会员v4的分享  
代码是这样的  
import re  
import pandas as pd  
import logging  
from typing import Dict, List  
import os  
import datetime  
from bs4 import BeautifulSoup

# 数据库容器初始化

dbA = {  
‘meta’: , # 存储元数据信息  
‘words’: , # 存储所有词条  
‘definitions’: , # 存储词条定义  
‘examples’: , # 存储例句  
‘wordsNoExamples’: ,# 存储没有例句的词条  
‘wordsNoDefCn’: , # 存储没有中文释义的词条  
‘entries’: , # 存储词条内容  
}

# 数据库B用于存储提取的详细信息

dbB = {  
‘pronunciation’: # 只保留发音列  
}

def txt2db(path: str, dbA: Dict):  
“”“将文本文件转换为数据库”“”  
try:  
with open(path, ‘r’, encoding=‘utf-8’) as f:  
lines = f.readlines()

```
    print(f"文件总行数: {len(lines)}")
    
    # 初始化数据库列表
    dbA['words'] = []
    dbA['definitions'] = []
    dbA['entries'] = [] # 添加entries列表
    
    current_entry = []
    
    for line in lines:
        line = line.strip()
        if not line: # 跳过空行
            continue
            
        # 如果是新词条（以字母开头）
        if line[0].isalpha():
            # 保存前一个词条
            if current_entry:
                entry_text = '\n'.join(current_entry)
                dbA['entries'].append(entry_text)
                
            # 开始新词条
            current_entry = [line]
        else:
            # 添加到当前词条
            current_entry.append(line)
            
    # 保存最后一个词条
    if current_entry:
        entry_text = '\n'.join(current_entry)
        dbA['entries'].append(entry_text)
        
    print(f"\n找到 {len(dbA['entries'])} 个词条")
    
    # 调试输出：查看前5个词条的内容
    print("\n前5个词条示例：")
    for i in range(min(5, len(dbA['entries']))):
        print(f"\n词条 {i+1}:")
        print("="*50)
        print(dbA['entries'][i])
        print("="*50)
        
except Exception as e:
    print(f"处理文件时出错: {str(e)}")

```

def extract\_info(dbA: Dict, dbB: Dict):  
“”“从数据库中提取单词、发音和词性”“”  
# 清空列表  
dbB[‘id’] =   
dbB[‘word’] =   
dbB[‘pronunciation’] =   
dbB[‘part\_of\_speech’] =   
dbB[‘split\_parts’] =

```
# 定义有效词性列表
valid_pos = {'noun', 'verb', 'adj', 'adv', 'pron', 'art', 'prep', 'conj', 'num', 'int'}

for entry_id, entry in enumerate(dbA['entries'], 1):
    # 提取单词
    word = ''
    if entry:
        first_line = entry.split('\n')[0].strip()
        word_match = re.match(r'^([A-Za-z0-9\s()]+?)(?:\*\1|\1)?(?:\s|$)', first_line)
        if word_match:
            word = word_match.group(1).strip()
        else:
            word = first_line.split()[0] if first_line.split() else ''
    
    # 先用\n\n分割，再用||分割
    main_parts = entry.split('\n\n')
    all_parts = []
    for part in main_parts:
        all_parts.extend(part.split('||'))
    
    # 清理每个部分
    all_parts = [part.strip() for part in all_parts if part.strip()]
    split_parts_text = ' || '.join(all_parts)
    
    # 存储所有找到的词性和发音
    found_pos = []
    pronunciations = []
    
    # 从第二部分开始查找词性和发音
    for i, part in enumerate(all_parts[1:], 1): # 从索引1开始
        # 提取发音（在每个部分开头到第一个/之前的内容）
        pron_match = re.search(r'^([^/]+)', part)
        if pron_match:
            pron = pron_match.group(1).strip()
            pronunciations.append(pron)
        else:
            pronunciations.append('')
        
        # 在当前部分中查找词性
        pos = ''
        parts = part.split('/')
        if len(parts) > 1:
            for p in parts[1:]:
                for valid_pos_item in valid_pos:
                    if p.startswith(valid_pos_item):
                        pos = valid_pos_item
                        found_pos.append((pos, pron))
                        break
                if pos:
                    break
    
    # 存储已添加的词性
    added_pos = set()
    
    # 添加记录
    if found_pos:
        # 为每个找到的词性添加一条记录（如果不重复）
        for pos, pron in found_pos:
            # 只有当词性不在已添加列表中时才添加
            if pos not in added_pos:
                dbB['id'].append(entry_id)
                dbB['word'].append(word)
                dbB['pronunciation'].append(pron)
                dbB['part_of_speech'].append(pos)
                dbB['split_parts'].append(split_parts_text)
                # 将词性添加到已添加集合中
                added_pos.add(pos)
    else:
        # 如果没有找到任何词性，添加一个空记录
        dbB['id'].append(entry_id)
        dbB['word'].append(word)
        dbB['pronunciation'].append(pronunciations[0] if pronunciations else '')
        dbB['part_of_speech'].append('')
        dbB['split_parts'].append(split_parts_text)
    
    # 打印调试信息（前5个词条）
    if entry_id <= 5:
        print(f"\n正在处理第 {entry_id} 个词条...")
        print("="*50)
        print(f"原文:\n{entry[:200]}...")
        print(f"首行: [{first_line}]")
        print(f"分割部分数: {len(all_parts)}")
        print(f"分割部分: {split_parts_text}")
        print(f"提取的单词: [{word}]")
        print(f"找到的词性和发音:")
        for pos, pron in found_pos:
            print(f" 发音: [{pron}] 词性: [{pos}]")
        print("="*50)

print("\n" + "="*50)
print("处理完成！")
print(f"总共处理了 {len(dbB['word'])} 个词条")
print("前5个词条的结果:")
for i in range(min(5, len(dbB['word']))):
    print(f"{dbB['word'][i]} -> {dbB['pronunciation'][i]} [{dbB['part_of_speech'][i]}]")
print("="*50 + "\n")

```

def main():  
input\_file = r"C:\Users\yyw18\Downloads\处理ok牛津中阶.txt"  
timestamp = datetime.datetime.now().strftime(“%Y%m%d\_%H%M%S”)  
output\_file = os.path.join(os.path.expanduser(“~”), “Desktop”, f"dictionary\_data\_{timestamp}.xlsx")

```
# 处理文件
txt2db(input_file, dbA)

# 提取信息
extract_info(dbA, dbB)

# 保存到Excel（包含词性列）
df = pd.DataFrame(dbB)
df.to_excel(output_file, index=False, sheet_name='词典数据')

print(f"\n处理完成！数据已保存到:\n{output_file}")

```

if **name** == “ **main** ”:  
main()

---

<div class="post-metadata">

作者： ![yium3023](https://forumcdn.freemdict.com/letter_avatar_proxy/v4/letter/y/35a633/32.png) [@yium3023](https://forum.freemdict.com/u/yium3023)\
发布日期： [2024 年12 月 31 日 04:06 UTC](https://forum.freemdict.com/t/topic/35290/4 "2024-12-31T04:06:52Z")

</div>

每个词典都不一样，但思路好像都是用数据库然后导出成excel，用好数据库能实现后面的功能，我一开始试了半天，永远生成的只有一行的分割，只有用数据库然后导出才有多行

---

<div class="post-metadata">

作者： ![yium3023](https://forumcdn.freemdict.com/letter_avatar_proxy/v4/letter/y/35a633/32.png) [@yium3023](https://forum.freemdict.com/u/yium3023)\
发布日期： [2024 年12 月 31 日 04:09 UTC](https://forum.freemdict.com/t/topic/35290/5 "2024-12-31T04:09:22Z")

</div>

我纯没学过python，只是高中被迫学了点vb

---

<div class="post-metadata">

作者： ![Waylon](https://forumcdn.freemdict.com/user_avatar/forum.freemdict.com/waylon/32/55396_2.png) [@Waylon](https://forum.freemdict.com/u/Waylon)\
发布日期： [2024 年12 月 31 日 08:39 UTC](https://forum.freemdict.com/t/topic/35290/6 "2024-12-31T08:39:31Z")

</div>

[ParseMWALD\_v1.9.py](https://forum.freemdict.com/uploads/short-url/nvzUe4LAFpoqH59WsD6hxfDSLhw.py) (18.3 KB)  
这是后来我自己写的，本来还不打算发出来，还有很多地方要改，但是你可以参考下

---

<div class="post-metadata">

作者： ![jcz777](https://forumcdn.freemdict.com/user_avatar/forum.freemdict.com/jcz777/32/60576_2.png) [@jcz777](https://forum.freemdict.com/u/jcz777)\
发布日期： [2024 年12 月 31 日 09:16 UTC](https://forum.freemdict.com/t/topic/35290/7 "2024-12-31T09:16:00Z")

</div>

mdx转txt，  
txt转csv。
