java 中文拼写检查_How to Write a Spelling Corrector用java 写拼写检查器 Java实现 以备查验...

import java.io.*;

import java.util.*;

import java.util.regex.*;

class Spelling {

private final HashMap nWords = new HashMap();

public Spelling(String file) throws IOException {

BufferedReader in = new BufferedReader(new FileReader(file));

Pattern p = Pattern.compile("\\w+");

for(String temp = ""; temp != null; temp = in.readLine()){

Matcher m = p.matcher(temp.toLowerCase());

while(m.find())

nWords.put((temp = m.group()), nWords.containsKey(temp) ? nWords.get(temp) + 1 : 1);

}

in.close();

//System.out.println(nWords.size());

}

private final ArrayList edits(String word) {

ArrayList result = new ArrayList();

for(int i=0; i < word.length(); ++i) result.add(word.substring(0, i) + word.substring(i+1));

for(int i=0; i < word.length()-1; ++i) result.add(word.substring(0, i) + word.substring(i+1, i+2) + word.substring(i, i+1) + word.substring(i+2));

for(int i=0; i < word.length(); ++i) for(char c='a'; c <= 'z'; ++c) result.add(word.substring(0, i) + String.valueOf(c) + word.substring(i+1));

for(int i=0; i <= word.length(); ++i) for(char c='a'; c <= 'z'; ++c) result.add(word.substring(0, i) + String.valueOf(c) + word.substring(i));

return result;

}

public final String correct(String word) {

//如果词袋子里面含有这个词直接返回

if(nWords.containsKey(word)) return word;

//没有这个词的话,那就认为这个词拼写错误 找到所有的可能的基于这个词的可能词汇

ArrayList list = edits(word);

HashMap candidates = new HashMap();

//在猜想的词汇表中如果与字典中的词重合,那就放进候选列表里面

for(String s : list) if(nWords.containsKey(s)) candidates.put(nWords.get(s),s);

//如果在候选列表里面有候选

if(candidates.size() > 0) return candidates.get(Collections.max(candidates.keySet()));

//没有候选的时候怎么办?

for(String s : list)

for(String w : edits(s))

//进行第二次匹配,拿出猜想的可能词汇,再进行一次猜想, 再不行的话,直接返回原来的word

if(nWords.containsKey(w))

candidates.put(nWords.get(w),w);

return candidates.size() > 0 ? candidates.get(Collections.max(candidates.keySet())) : word;

}

public static void main(String args[]) throws IOException {

if(args.length > 0) System.out.println((new Spelling("big.txt")).correct(args[0]));

}

}

http://raelcunha.com/spell-correct.php

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值