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

如何在PyCharm中显示有限状态转换器(FST)状态图?

解决NLTK FST状态转移图无法显示的问题

问题代码

# import the fst module
from nltk.draw import *
from nltk.nltk_contrib.fst.fst import *
# import the string module
import string

# Define a list of all vowels for convenience
vowels = ['a', 'e', 'i', 'o', 'u']
special = ['?', '!', '#', '$', '&']

# Instantiate an FST object with some name
f = FST('devowelizer2')

# All we need is a single state ...
f.add_state('1')
f.add_state('2')
f.add_state('3')

# and this same state is the initial and the final state
f.initial_state = '1'
f.set_final('1')
f.set_final('2')
f.set_final('3')
# Now, we need to add an arc for each letter; if the letter is a vowel
# then transition outputs nothing but otherwise it outputs the same
# letter that it consumed.
for letter in string.ascii_lowercase:

    if letter in vowels:
        f.add_arc('1', '3', (letter), ('V'))
        f.add_arc('2', '3', (letter), ('V'))
        f.add_arc('3', '3', (letter), ('V'))


    elif letter in special:
        f.add_arc('1', '1', (letter), ('I'))
        f.add_arc('2', '1', (letter), ('I'))
        f.add_arc('3', '1', (letter), ('I'))

    else:
        f.add_arc('1', '2', (letter), ('C'))
        f.add_arc('2', '2', (letter), ('C'))
        f.add_arc('3', '2', (letter), ('C'))

# Evaluate it on some example words (.join is the reverse of split(), it joins two items together)
# Outputs 'vwl'
# print(''.join(f.transduce(['v', 'o', 'w', 'e', 'l'])))

# without join : output is a separate characters in a list
print(f.transduce(['v', 'o', 'w', 'e', 'l', '#']))

# Outputs 'xcptn'
print(''.join(f.transduce('e x c e p t i o n'.split())))

# Outputs 'cnsnnt'
print(''.join(f.transduce('c o n s o n a n t'.split())))

disp = FSTDisplay(f)
# disp.transduce("e x c e p t i o n".split())
# disp.loop()

问题描述

在PyCharm中运行上述代码可正常输出结果,但无法显示状态转移图。已手动将nltk_cont文件夹添加至site-packages目录下的nltk文件夹中,问题仍未解决,期望显示出目标状态图。

解决步骤

  • 启用图形事件循环:代码末尾的disp.loop()被注释,这是维持图形窗口显示的关键。取消注释相关行,修改后代码末尾应为:
    disp = FSTDisplay(f)
    disp.transduce("e x c e p t i o n".split())
    disp.loop()
    
  • 检查Tkinter依赖:NLTK绘图依赖Tkinter,确保当前Python环境已安装该库:
    • Windows系统通常自带,无需额外安装;
    • Linux系统可通过包管理器安装(如apt-get install python3-tk);
    • MacOS可通过Homebrew安装(brew install python-tk)。
  • 尝试终端运行脚本:PyCharm的运行环境可能限制图形显示,直接在系统终端执行脚本,看是否能正常弹出状态图窗口。
  • 验证nltk_cont路径正确性:确认nltk_cont放置在site-packages/nltk/nltk_contrib路径下,可在代码开头添加import nltk; print(nltk.nltk_contrib)验证模块是否能正常导入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 06:15:38