分析英文语料库,计算单词数量,格式化为json

1. 得到语料库

这里使用的是英文小说作为语料库分析。

2. 一次性读取txt文件

public static byte[] getText() throws IOException {
    File file = new File("H:\\test2.txt");
    Long fileLength = file.length();
    byte[] fileContent = new byte[fileLength.intValue()];
    try {
        FileInputStream is = new FileInputStream(file);
        is.read(fileContent);
        is.close();
    } catch (Exception e) {
    }
    return fileContent;
}

这里返回的是一个byte[]数组,可以直接使用new String(byte[]数组)进行读取。具体方法见标题4。

3. 统计单词方法

public static void CountWords(String str) throws IOException {

    //存放单词的统计结果
        List<String> countForWord = new ArrayList<String>() ;
    
        Map<String, Integer> map=new HashMap<String, Integer>();        
        Pattern p=Pattern.compile("\\b[a-zA-Z-]+\\b");//正则表达式
        Matcher m=p.matcher(str);
        while(m.find()){
            String mstr=m.group();
            if(map.containsKey(mstr)){
                //相同的key,后者就会覆盖,次数+1
                map.put(mstr,map.get(mstr)+1);
            }else{
                map.put(mstr, 1);
            }
        }
        
//      Set<Entry<String, Integer>> entrySet = map.entrySet();
//      Iterator<Entry<String,Integer>> it=entrySet.iterator();
//      while(it.hasNext()){
//          Entry<String, Integer> next = it.next();
//          System.out.println(next.getKey()+" 个数:"+next.getValue());
//      }
        
        //map.entrySet()方法:返回一个Set集合,这个集合的类型为:Map.Entry
        //it是定义一个迭代器,用于遍历set集合。
        Set entrySet = map.entrySet();
        Iterator it = entrySet.iterator();
        
        //进行迭代遍历
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String tmp = entry.getKey() + " " + entry.getValue() ; 
            //统计结果按行存入countForWord中。
            countForWord.add(tmp);
        }
        
        //写入txt文件中。
        FileWriter fw = new FileWriter(new File("H:\\test3.txt"));
        BufferedWriter bw = new BufferedWriter(fw);
        for (String str1 : countForWord) {
            //换行 \r\n
            bw.write(str1+"\r\n");
        }
        bw.close();
        fw.close();
    }

4. 入口方法,执行程序

public static void main(String[] args) throws IOException {
        //将byte[]数组转换成String
        String str = new String(getText());
        //全部转换成小写
        str = str.toLowerCase();
        //调用方法
        CountWords(str);
    }

注意修改文件路径

结果:


统计结果

5. 转换为json格式

上一篇固定txt格式转json链接

这里用的就是这个方法。

package zidongjiucuo;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSON;
import zidongjiucuo.ClassA;

public class Test {

    public static void main(String[] args) throws IOException {
        InputStreamReader ins = new InputStreamReader(new FileInputStream("H:\\test3.txt"));
        BufferedReader br = new BufferedReader(ins);
        List<String> list = new ArrayList<String>();
        //存放java对象
        List<ClassA> tlist = new ArrayList<ClassA>();
        String line = null;
        while((line = br.readLine()) != null) {
            list.add(line);
        }
        br.close();
        System.out.println(list.size());
        for (String str : list) {
            String[] arrStr = str.split("\\s+");
            ClassA classA = new ClassA();
            classA.setWord(arrStr[0]);
            classA.setTimes(Integer.parseInt(arrStr[1]));
            tlist.add(classA);
        }
        String json = JSON.toJSONString(tlist);
        System.out.println(json);
        
        File txtToJson = new File("H:\\json1.json");
        txtToJson.createNewFile();
        BufferedWriter out = new BufferedWriter(new FileWriter(txtToJson));  
        out.write(json); 
        out.flush(); // 把缓存区内容压入文件  
        out.close(); // 最后记得关闭文件  
    }
}

同样需要注意修改路径。
上方使用fastTojson,需要定义一个bean类。在上方main方法中就是ClassA

classA bean类
package zidongjiucuo;  
 
public class ClassA {
    public String word;
    public int times;
    public String getWord() {
        return word;
    }
    public void setWord(String word) {
        this.word = word;
    }
    public int getTimes() {
        return times;
    }
    public void setTimes(int times) {
        this.times = times;
    }
}

6. 运行该方法,查看结果

json结果

7. 总结

原理主要涉及到Map数据类型、entrySet、文件的读写等。
可以将以上方法改进、整理,使其可读性更强。
接下来就要将json串存入数据库,计算每个单词的出现概率等,用于下一步的毕业设计。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容