You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Pythainlp自定义词典泰语分词运行过慢如何优化?

问题核心原因及优化方案

1. 首要性能优化:将自定义词典构建逻辑移到函数外

当前耗时过长的核心原因是你把自定义trie词典的构建逻辑写在了text_tokenize函数内部,每次处理一条样本都会重新加载泰语通用词库、合并自定义词、重新生成trie结构,这部分操作全局只需要执行1次,重复执行会浪费90%以上的计算资源。
首先执行全局初始化代码,这部分仅运行一次:

from pythainlp.corpus.common import thai_words
from pythainlp.util import dict_trie
from pythainlp import word_tokenize
from pythainlp.corpus import thai_stopwords

# 全局仅构建1次自定义词典
new_words = {'คนละครึ่ง', 'ยืนยันตัวตน', 'เติมเงิน', 'เราชนะ', 'เป๋าตัง', 'แอปเป๋าตัง'}
words = new_words.union(thai_words())
custom_dictionary_trie = dict_trie(words)
# 停用词转集合,in查询效率远高于列表
thai_stopword_set = set(thai_stopwords())
# 标点转集合,加速过滤判断
punctuation_set = set(r'''.?!,;:-_[]()'/<>{}@#$&%~*ๆฯ''')

调整分词函数,直接复用预构建的词典:

def text_tokenize(Mention):
    # 指定newmm引擎,是pythainlp支持自定义词典的最快分词引擎
    return word_tokenize(Mention, custom_dict=custom_dictionary_trie, keep_whitespace=False, engine='newmm')

2. 修复text_process的逻辑错误并优化

你原代码有两处逻辑错误,既会导致结果不准也会额外消耗性能:

  • 标点过滤的判断逻辑写错,原写法if u not in puncuations and ('ๆ', 'ฯ')永远为真,等于没过滤这两个泰语特殊符号
  • 停用词判断word.lower没加括号,等于判断的是方法对象而非小写后的单词,停用词过滤完全未生效
    优化后的处理函数:
def text_process(Mention):
    # 过滤标点
    final = "".join(u for u in Mention if u not in punctuation_set)
    # 调用分词
    final = text_tokenize(final)
    # 直接过滤停用词后拼接,省掉多余的split操作
    final = " ".join(word for word in final if word.lower() not in thai_stopword_set)
    return final

dff['text_tokens'] = dff['Mention'].apply(text_process) 

3. 大数据量额外加速方案

如果你的数据集超过10万条,还可以加这层优化:
安装swifter库,将apply逻辑改成dff['Mention'].swifter.apply(text_process),工具会自动判断是否启用多进程加速apply操作,速度还能提升2-4倍。


内容的提问来源于stack exchange,提问作者Mint THnk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 03:36:03