zoukankan      html  css  js  c++  java
  • How to Write a Spelling Corrector用java 写拼写检查器 Java实现 以备查验

    import java.io.*;
    import java.util.*;
    import java.util.regex.*;

    class Spelling {

    private final HashMap<String, Integer> nWords = new HashMap<String, Integer>();

    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<String> edits(String word) {
    ArrayList<String> result = new ArrayList<String>();
    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<String> list = edits(word);
    HashMap<Integer, String> candidates = new HashMap<Integer, String>();
    //在猜想的词汇表中如果与字典中的词重合,那就放进候选列表里面
    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

  • 相关阅读:
    在zend framework框架中try{}catch(Exception e){}的跳转问题
    【上】安全HTTPS-全面具体解释对称加密,非对称加密,数字签名,数字证书和HTTPS
    iOS 图像处理-剪裁图像
    Delphi DBGrid记录全选和反选拖动处理
    在DbGrid中,不按下Ctrl,单击鼠标如何实现多选?谢谢
    在DBGrid中实现多选功能
    回车跳到下一个EDIT
    远程控制篇:用Delphi模拟键盘输入/鼠标点击
    SQL的拼接语句在DELPHI中怎么写
    Delphi DbGridEh实现表格没有内容的渐变效果
  • 原文地址:https://www.cnblogs.com/mrcharles/p/4744842.html
Copyright © 2011-2022 走看看