0

我试过这个库,在堆栈溢出的一篇文章中建议,

我已将 lib 的 jar 添加到我的构建路径中,但我无法使用语言的配置文件初始化 DetectorFactory 类。

这是处理检测的类,如他们的一个示例中所建议的:

class LanguageDetector {
    public void init(String profileDirectory) throws LangDetectException {
        DetectorFactory.loadProfile(profileDirectory);
    }
    public String detect(String text) throws LangDetectException {
        Detector detector = DetectorFactory.create();
        detector.append(text);
        return detector.detect();
    }
    public ArrayList<Language> detectLangs(String text) throws LangDetectException {
        Detector detector = DetectorFactory.create();
        detector.append(text);
        return detector.getProbabilities();
    }
}

所有语言配置文件都存储在 myProject/profiles 下。尝试实例化该类会使我的应用程序崩溃,而不会向 logcat 提供任何有用的消息

调用类():

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        context = this.getActivity().getApplicationContext();
/*        LanguageDetector detector = null;
        try {
            detector.init("/waggle/profiles");
        } catch (LangDetectException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/
        new GetDataTask().execute(context);

    }
4

1 回答 1

0

将方法更改LanguageDetector为静态:

class LanguageDetector {
    public static void init(String profileDirectory) throws LangDetectException {
        DetectorFactory.loadProfile(profileDirectory);
    }
    public static String detect(String text) throws LangDetectException {
        Detector detector = DetectorFactory.create();
        detector.append(text);
        return detector.detect();
    }
    public static ArrayList<Language> detectLangs(String text) throws LangDetectException {
        Detector detector = DetectorFactory.create();
        detector.append(text);
        return detector.getProbabilities();
    }
}

并使用如下:

try {
    LanguageDetector.init("/waggle/profiles"); // <-- Are you sure the profiles are at this location???
} catch (LangDetectException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

String detectedLanguage = null;
try {
    detectedLanguage = LanguageDetector.detect("Dies ist ein Beispiel in Deutsch.");
} catch (LangDetectException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

if (detectedLanguage != null) {
    // Implement your logic here
}
于 2013-07-20T17:21:08.390 回答