gpt4 book ai didi

java - 使用 com.cybozu.labs.langdetect 包检测字符串的语言

转载 作者:行者123 更新时间:2023-11-29 04:21:02 25 4
gpt4 key购买 nike

我正在寻找一个小示例代码来检测 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com