我正在寻找一个小示例代码来检测 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());
}
}
最佳答案
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"
关于java - 使用 com.cybozu.labs.langdetect 包检测字符串的语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49181637/