2

我正在寻找一个小示例代码来检测 JAVA 中字符串的语言。为此,我下载并导入了以下 GitHub 项目:https ://github.com/shuyo/language-detection

不幸的是,我正在努力阅读 API,而且我不知道如何让我的代码正常工作。非常感谢帮助。继承人我到目前为止。我得到一个 NullPointerException 因为我不知道如何正确初始化检测器。非常感谢您的帮助。

import com.cybozu.labs.langdetect.*;

public class DetectLanguage {

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

        String sample = "Comment vous appelez-vous?";   // french demo text
        Detector d = new Detector(null);                // initialize detector
        d.append(sample);
        System.out.println(d.detect());
    }
}
4

1 回答 1

4

构造Detector函数签名是:

public Detector(DetectorFactory factory)

所以看看DetectorFactory, 是一个没有getInstance()方法的单例:
你应该像这样创建你的检测器:

Detector d = DetectorFactory.create();

但如果你只是这样做,是不够的......

com.cybozu.labs.langdetect.LangDetectException: need to load profiles

所以最小和完整的工作示例是:

try {
    String sample = "Comment vous appelez-vous?";
    // Prepare the profile before
    DetectorFactory.loadProfile("/language-detection/profiles");
    // Create the Detector
    Detector d = DetectorFactory.create();
    d.append(sample);

    System.out.println(d.detect()); // Ouput: "fr"
} catch (LangDetectException e) {
    e.printStackTrace();
}

当您测试这些字符串时:

String sample = "Comment vous appelez-vous ?"; // "fr"
String sample = "Buongiorno come stai ?"; // "it"
String sample = "Hello how are you ?"; // "en"
于 2018-03-09T12:52:20.507 回答