如何使用Perl的Text::Aspell模块实现文本拼写检查功能
你可以用正则匹配提取单词的思路替代拆分非单词字符的方案,不需要手动维护标点符号过滤列表,代码更简洁健壮:
use strict; use warnings; use Text::Aspell; my $input = "This doesn't look too bad. Me&you. with/without. 1..2..3..go!"; my $aspell = Text::Aspell->new(); $aspell->set_option('lang', 'en'); # 提取所有合法英文单词,自动过滤标点、数字、特殊符号 while ($input =~ /\p{Letter}+(?:['’]\p{Letter}+)*/g) { my $word = $&; print "$word: ", $aspell->check($word), "\n"; }
正则逻辑说明:
\p{Letter}匹配任意Unicode字母,比[a-zA-Z]适用范围更广,兼容多语言拼写检查场景(?:['’]\p{Letter}+)*匹配0次或多次「撇号+字母」的组合,适配doesn't、Jenny's这类带合法撇号的英文单词,同时不会匹配开头/结尾的撇号、连续撇号g修饰符全局遍历整个字符串提取所有匹配的单词
运行后输出结果和你手动指定拆分字符得到的正确结果完全一致。如果你的场景需要支持mother-in-law这类带连字符的合法单词,只需要把正则修改为/\p{Letter}+(?:['’-]\p{Letter}+)*/g即可,适配成本极低。
如果需要获取拼写错误单词的修正建议,可以扩展判断逻辑:
while ($input =~ /\p{Letter}+(?:['’]\p{Letter}+)*/g) { my $word = $&; if ($aspell->check($word)) { print "$word: 拼写正确\n"; } else { my @suggestions = $aspell->suggest($word); print "$word: 拼写错误,建议修正为:" . join('、', @suggestions) . "\n"; } }
内容的提问来源于stack exchange,提问作者Robert
相关产品推荐
相关产品推荐

