Java 计算示例文本文件中n克的频率

Java 计算示例文本文件中n克的频率,java,markov,Java,Markov,所以,我在Java中实现了一个马尔可夫随机文本生成器,我已经提取了文本文件中的n-gram,但现在我正在努力编写一个类,它给出文本中n-gram的出现次数(以及最终的概率) 这是我目前掌握的代码。有点乱,但这是一份草稿。 //这是主文件,我在其中解析文本并使用给定文本创建一个新的n-gram对象 import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Pat

所以,我在Java中实现了一个马尔可夫随机文本生成器,我已经提取了文本文件中的n-gram,但现在我正在努力编写一个类,它给出文本中n-gram的出现次数(以及最终的概率)

这是我目前掌握的代码。有点乱,但这是一份草稿。 //这是主文件,我在其中解析文本并使用给定文本创建一个新的n-gram对象

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;



public class Markov {

    public static String readCorpusToString(File fileName) {
        String corpus = " ";
        try {
            corpus = new String(Files.readAllBytes(Paths.get(String.valueOf(fileName))));
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return corpus;
    }

    public static void main(String[] args) {
        File text = new File(args[0]);
        String corpus = readCorpusToString(text);
        //System.out.println(corpus);
        Ngram test = new Ngram(3, corpus);
        for ( int i = 0; i <= corpus.length(); i++) {
            System.out.println(test.next());
        }



        }
}
导入java.io.File;
导入java.io.IOException;
导入java.nio.file.Files;
导入java.nio.file.path;
公共类马尔可夫{
公共静态字符串readCorpusToString(文件名){
字符串语料库=”;
试一试{
语料库=新字符串(Files.readAllBytes(path.get(String.valueOf(fileName)));
}
捕获(IOE异常){
e、 printStackTrace();
}
返回语料库;
}
公共静态void main(字符串[]args){
文件文本=新文件(args[0]);
字符串语料库=readCorpusToString(文本);
//系统输出打印语言(语料库);
Ngram测试=新的Ngram(3,语料库);
对于(int i=0;i
import java.util.Iterator;

public class Ngram implements Iterator<String> {

        String[] words;
        int pos = 0, n;

public Ngram(int n, String str) {
        this.n = n;
        words = str.split(" ");
        }

public boolean hasNext() {
        return pos < words.length - n + 1;
        }

public String next() {
        StringBuilder sb = new StringBuilder();
        for (int i = pos; i < pos + n; i++) {
            sb.append((i > pos ? " " : "") + words[i]);
        }
        pos++;
        return sb.toString();
        }

public void remove() {
        throw new UnsupportedOperationException();
        }




}