怎样写一个拼写检查器(java版)

下面是拼写检查器很好的文章,本文参照该文,将实现java版

http://blog.youxu.info/spell-correct.html


整个拼写检查器的基础就是贝叶斯概率模型

我简单的介绍一下它的工作原理. 给定一个单词, 我们的任务是选择和它最相似的拼写正确的单词. (如果这个单词本身拼写就是正确的, 那么最相近的就是它自己啦). 当然, 不可能绝对的找到相近的单词, 比如说给定 lates 这个单词, 它应该别更正为 late 呢 还是 latest 呢? 这些困难指示我们, 需要使用概率论, 而不是基于规则的判断. 我们说, 给定一个词 w, 在所有正确的拼写词中, 我们想要找一个正确的词 c, 使得对于 w 的条件概率最大, 也就是说:

argmax c P( c| w)
按照  贝叶斯理论  上面的式子等价于:
argmax c P( w| c) P( c) / P( w)
因为用户可以输错任何词, 因此对于任何 c 来讲, 出现 w 的概率 P(w) 都是一样的, 从而我们在上式中忽略它, 写成:
argmax c P( w| c) P( c)
这个式子有三个部分, 从右到左, 分别是:

1. P(c), 文章中出现一个正确拼写词 c 的概率, 也就是说, 在英语文章中, c 出现的概率有多大呢? 因为这个概率完全由英语这种语言决定, 我们称之为做 语言模型. 好比说, 英语中出现 the 的概率  P('the') 就相对高, 而出现  P('zxzxzxzyy') 的概率接近0(假设后者也是一个词的话).

2. P(w|c), 在用户想键入 c 的情况下敲成 w 的概率. 因为这个是代表用户会以多大的概率把 c 敲错成 w, 因此这个被称为 误差模型.

3. argmax c, 用来枚举所有可能的 c 并且选取概率最大的, 因为我们有理由相信, 一个(正确的)单词出现的频率高, 用户又容易把它敲成另一个错误的单词, 那么, 那个敲错的单词应该被更正为这个正确的.
有人肯定要问, 你笨啊, 为什么把最简单的一个 P( c | w ) 变成两项复杂的式子来计算? 答案是本质上 P(c|w) 就是和这两项同时相关的, 因此拆成两项反而容易处理. 举个例子, 比如一个单词 thew 拼错了. 看上去 thaw 应该是正确的, 因为就是把 a 打成 e 了. 然而, 也有可能用户想要的是 the, 因为 the 是英语中常见的一个词, 并且很有可能打字时候手不小心从 e 滑到 w 了. 因此, 在这种情况下, 我们想要计算  P( c | w ), 就必须同时考虑 c 出现的概率和从 c 到 w 的概率. 把一项拆成两项反而让这个问题更加容易更加清晰.


使用到的语料库为:big.txt.

代码github:https://github.com/dreamboy127/Spell_java


java 代码如下:


import java.util.*;
import java.io.*;
public class SpellCorrect{
    public static void readLines(String file, ArrayList<String> lines) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(new File(file)));
            String line = null;
            while ((line = reader.readLine()) != null) {
                lines.add(line);                                                            
            }                                                    
        } catch (FileNotFoundException e) {
            e.printStackTrace();
                                        
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();                                                          
                }
            }
        }                    
    }
        private static String readText(File file) { 
                String text = null;
                try
                {
                        InputStreamReader read = new InputStreamReader(new FileInputStream(file));
                        BufferedReader br = new BufferedReader(read);    
                        StringBuffer buff = new StringBuffer();     
                        while((text = br.readLine()) != null)
                {    
                                buff.append(text + "\r\n");    
                }    
                br.close();         
                text = buff.toString(); 
            }  
                catch(FileNotFoundException e)  
            {   
                        System.out.println(e);  
            }  
            catch(IOException e)  
            {   
                System.out.println(e);  
            }
               return text;
        }
    public static void tokenizeAndLowerCase(String line, ArrayList<String> tokens) {
    // TODO Auto-generated method stub
        StringTokenizer strTok = new StringTokenizer(line,"\r\n\t/\\\':\" ()[]{};.,#-_=!@$%^&*+1234567890");
        while (strTok.hasMoreTokens()) {
            String token = strTok.nextToken();
            tokens.add(token.toLowerCase().trim());
        }
    }
    public static void trainPrior(ArrayList<String> str,Map<String,Integer> map)
    {
        for(int i=0;i<str.size();i++)
        {
            if(map.containsKey(str.get(i)))
            {
                int tmp=map.get(str.get(i));
                map.put(str.get(i),1+tmp);
            }
            else
                map.put(str.get(i),1);
        }
    }
    public static Set<String> Edit1(String str){
        Set<String> array=new HashSet<String>();
        for(int i=0;i<str.length();i++)//delete
        {
            String tmpstr=str.substring(0,i)+str.substring(i+1,str.length());
            array.add(tmpstr);
        }
        
        for(int i=0;i<str.length();i++)//insert
        {
            for(char x='a';x<='z';x++)
            {
                String tmpstr=str.substring(0,i)+x+str.substring(i,str.length());
                array.add(tmpstr);
            }   
        }
        for(int i=0;i<str.length()-1;i++)//trans
        {
            String tmpstr=str.substring(0,i)+str.charAt(i+1)+str.charAt(i)+str.substring(i+2,str.length());
            array.add(tmpstr);
        }
        for(int i=0;i<str.length();i++)//convert
        {
            for(char x='a';x<='z';x++)
            {
                String tmpstr=str.substring(0,i)+x+str.substring(i+1,str.length());
                array.add(tmpstr);
            }
        }
        return array;
    }
    public static Set<String> Edit2(String str){
        Set<String> array=new HashSet<String>();
        array=Edit1(str);
        Set<String> array2=new HashSet<String>();
        Iterator<String> iter=array.iterator();
        while(iter.hasNext())
        {
            String str1=iter.next();
            array2.addAll(Edit1(str1));
        }
        return array2;
    }
    public static boolean kowns(Set<String> checkset,Set<String> wordset)
    {
        Iterator<String> iter=checkset.iterator();
        while(iter.hasNext())
        {
            String str=iter.next();
            if(!wordset.contains(str))
                iter.remove();
        }
        return checkset.size()>0;
    }
    public static void main(String[] args){
        String text=readText(new File("big.txt"));
        ArrayList<String> s=new ArrayList<String>();
        tokenizeAndLowerCase(text,s);
        Map<String,Integer> map=new HashMap<String,Integer>();
        trainPrior(s,map);
        Set<String> keys=map.keySet();
 //       System.out.println(map.size());
        Scanner scan=new Scanner(System.in);
        System.out.println("spell correct starting");
        while(true)
        {
            System.out.println("please input a term:");
            String str=scan.next();
            if("q".equals(str))
                break;
            Set<String> edit1=Edit1(str);
            Set<String> edit2=Edit2(str);
            boolean flag=kowns(new HashSet<String>(Arrays.asList(str)),keys);
            if(flag)
                return;
            Set<String> edit=edit1;
            flag=kowns(edit,keys);
            if(!flag)
            {
                edit=edit2;
                flag=kowns(edit,keys);
            }
            Iterator<String> iter=edit.iterator();
            int max=0;
            int tmp=1;
            String maxStr=null;
            while(iter.hasNext())
            {
                String tmpStr = iter.next();
//            System.out.println(tmpStr);
                tmp=map.get(tmpStr);

                if(max<tmp)
                {
                    maxStr=tmpStr;
                    max=tmp;
                }
            }
            System.out.println(maxStr);
        }
        System.out.println("spell correct ending");
//        Set<Map.Entry<String,Integer>> allSet=null;
//        allSet=map.entrySet();
//        for(Map.Entry<String,Integer> me : allSet)
//            System.out.println(me.getKey()+"-->"+me.getValue());
    }
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Trie树是一种树形数据结构,它主要用于字符串的存储和查找。Trie树的每个节点代表一个字符,根节点不存储任何字符,其他节点代表一个字符串的一部分。在Trie树中,如果一个节点的所有子节点都是叶节点,则该节点表示一个完整的字符串。 下面是一段Java代码,实现了一个简单的Trie树: ``` class TrieNode { private TrieNode[] children = new TrieNode[26]; private boolean isEnd; public TrieNode() {} public TrieNode[] getChildren() { return children; } public void setEnd() { isEnd = true; } public boolean isEnd() { return isEnd; } } class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } public void insert(String word) { TrieNode node = root; for (int i = 0; i < word.length(); i++) { int j = word.charAt(i) - 'a'; if (node.getChildren()[j] == null) { node.getChildren()[j] = new TrieNode(); } node = node.getChildren()[j]; } node.setEnd(); } public boolean search(String word) { TrieNode node = root; for (int i = 0; i < word.length(); i++) { int j = word.charAt(i) - 'a'; if (node.getChildren()[j] == null) { return false; } node = node.getChildren()[j]; } return node.isEnd(); } public boolean startsWith(String prefix) { TrieNode node = root; for (int i = 0; i < prefix.length(); i++) { int j = prefix.charAt(i) - 'a'; if (node.getChildren()[j] == null) { return false; } node = node.getChildren()[j]; } return true; } } ``` 该代码实现了一个Trie树,其中TrieNode ### 回答2: Trie树,也叫字典树或前缀树,是一种用于高效存储和检索字符串的数据结构。下面是使用Java一个简单Trie树的代码示例: ```java class TrieNode { private TrieNode[] children; private boolean isEndOfWord; public TrieNode() { children = new TrieNode[26]; // 26个字母 isEndOfWord = false; } } class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } public void insert(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); int index = ch - 'a'; if (current.children[index] == null) { current.children[index] = new TrieNode(); } current = current.children[index]; } current.isEndOfWord = true; } public boolean search(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); int index = ch - 'a'; if (current.children[index] == null) { return false; } current = current.children[index]; } return current.isEndOfWord; } public boolean startsWith(String prefix) { TrieNode current = root; for (int i = 0; i < prefix.length(); i++) { char ch = prefix.charAt(i); int index = ch - 'a'; if (current.children[index] == null) { return false; } current = current.children[index]; } return true; } } ``` 在上述代码中,我们使用了两个类:TrieNode和Trie。TrieNode表示Trie树中的每个节点,包含一个26个元素的数组来存储子节点和一个布尔变量isEndOfWord来表示当前节点是否是一个单词的结尾。Trie类是Trie树的实现,包含了插入、搜索和前缀搜索三个方法。 在插入方法中,我们首先从根节点开始,遍历插入的字符串的每个字符。通过计算字符在字母表中的位置,我们可以将其作为TrieNode数组的索引,以此构造Trie树的路径。最后,将叶子节点的isEndOfWord设置为true,表示该路径对应的字符串在Trie树中存在。 在搜索方法中,我们同样从根节点开始,遍历待搜索的字符串的每个字符。如果遇到某个字符在Trie树当前节点的子节点中不存在,则说明该字符串不存在于Trie树中,返回false。如果成功遍历完所有字符,并且叶子节点对应的isEndOfWord为true,则说明该字符串存在于Trie树中,返回true。 在前缀搜索方法中,与搜索方法类似,只是在遍历完所有字符后不进行isEndOfWord的判断,始终返回true。这是因为前缀搜索只需要判断给定字符串的前缀是否存在于Trie树中,无需判断是否是一个完整单词。 通过上述样例代码,我们可以实现一个简单的Trie树,并且能够进行插入、搜索和前缀搜索等操作。Trie树的优势在于其高效的字符串存储和检索性能,特别适用于需要进行前缀搜索的场景,如自动补全、拼纠错等应用。 ### 回答3: Trie树(也称为字典树或前缀树)是一种树形数据结构,用于高效地存储和搜索字符串集合。下面是用Java的简单Trie树代码段: ```java class TrieNode { private TrieNode[] children; private boolean isEndOfWord; public TrieNode() { children = new TrieNode[26]; // 26个小字母 isEndOfWord = false; } } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } public void insert(String word) { TrieNode currentNode = root; for (int i = 0; i < word.length(); i++) { int index = word.charAt(i) - 'a'; if (currentNode.children[index] == null) { currentNode.children[index] = new TrieNode(); } currentNode = currentNode.children[index]; } currentNode.isEndOfWord = true; } public boolean search(String word) { TrieNode currentNode = root; for (int i = 0; i < word.length(); i++) { int index = word.charAt(i) - 'a'; if (currentNode.children[index] == null) { return false; } currentNode = currentNode.children[index]; } return currentNode != null && currentNode.isEndOfWord; } public boolean startsWith(String prefix) { TrieNode currentNode = root; for (int i = 0; i < prefix.length(); i++) { int index = prefix.charAt(i) - 'a'; if (currentNode.children[index] == null) { return false; } currentNode = currentNode.children[index]; } return true; } } ``` 上述代码实现了一个简单的Trie树。Trie树的核心部分是`TrieNode`类,每个节点包含一个长度为26的子节点数组`children`,以及一个`boolean`类型的`isEndOfWord`字段,表示当前节点是否为一个单词的结尾。 `Trie`类是Trie树的主要类,主要提供插入、搜索和前缀搜索功能。在插入操作中,我们从根节点开始遍历字符串的每个字符,并根据字符的ASCII值索引到对应的子节点位置。如果当前节点的子节点为空,则创建一个新节点,并将当前节点更新为新节点。插入完成后,我们将最后一个节点的`isEndOfWord`字段设置为`true`,表示一个单词的结尾。 在搜索操作中,我们也是从根节点开始遍历字符串的每个字符,并根据字符的ASCII值索引到对应的子节点位置。如果遍历过程中发现某个字符的子节点为空,则返回`false`,表示找不到对应的单词。最后,我们检查最后一个字符的节点是否为空,并查看其`isEndOfWord`字段是否为`true`,来确定搜索操作的结果。 在前缀搜索操作中,逻辑与搜索操作类似,只是在找到对应的子节点位置时不需要判断`isEndOfWord`字段,只需保证一直存在就行。 通过这样的Trie树数据结构,我们可以高效地存储和搜索大量的字符串集合,具有较低的时间复杂度。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值