使用langdetect进行Java语言检测 - 如何加载配置文件?

IAm*_*aja 6 java jar classpath language-detection

我试图用所谓的Java库langdetect托管在这里.它使用起来既不容易:

Detector detector;
String langDetected = "";
try {
    String path = "C:/Users/myUser/Desktop/jars/langdetect/profiles";
    DetectorFactory.loadProfile(path);
    detector = DetectorFactory.create();
    detector.append(text);
    langDetected = detector.detect();
} 
catch (LangDetectException e) {
    throw e;
}

return langDetected;
Run Code Online (Sandbox Code Playgroud)

除了相对于所述DetectFactory.loadProfile方法.当我传递一个绝对文件路径时,这个库工作得很好,但最终我认为我需要将我的代码和langdetect配套profiles目录打包在同一个JAR文件中:

myapp.jar/
    META-INF/
    langdetect/
        profiles/
            af
            bn
            en
            ...etc.
    com/
        me/
            myorg/
                LangDetectAdaptor --> is what actually uses the code above
Run Code Online (Sandbox Code Playgroud)

我将确保LangDetectAdaptor位于其中的内容myapp.jar提供了在运行时工作所需的依赖项langdetect.jarjsonic.jar依赖项langdetect.但是我很困惑我需要传递给我的DetectFactory.loadProfile工作:

  • langdetectJAR附带了profiles目录,但你需要从你的JAR中初始化.那么我是否要复制profiles目录并将其放入我的JAR中(就像我上面所说的那样),或者有没有办法将其保留在里面langdetect.jar但是从我的代码中访问它?

在此先感谢您的帮助!

编辑:我认为这里的问题是langdetect 附带profiles目录,但后来要求您从JAR内部初始化它.API可能会受益于稍微改变一下,只考虑profiles自己的配置,然后提供方法,比如DetectFactory.loadProfiles().except("fr")你不希望它初始化法语等等.但这仍然无法解决我的问题!

Mar*_*ler 5

我也有同样的问题.您可以使用JarUrlConnectionJarEntry从LangDetect jar加载配置文件.请注意,在此示例中,我使用的是Java 7资源管理.

    String dirname = "profiles/";
    Enumeration<URL> en = Detector.class.getClassLoader().getResources(
            dirname);
    List<String> profiles = new ArrayList<>();
    if (en.hasMoreElements()) {
        URL url = en.nextElement();
        JarURLConnection urlcon = (JarURLConnection) url.openConnection();
        try (JarFile jar = urlcon.getJarFile();) {
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                String entry = entries.nextElement().getName();
                if (entry.startsWith(dirname)) {
                    try (InputStream in = Detector.class.getClassLoader()
                            .getResourceAsStream(entry);) {
                        profiles.add(IOUtils.toString(in));
                    }
                }
            }
        }
    }

    DetectorFactory.loadProfile(profiles);
    Detector detector = DetectorFactory.create();
    detector.append(text);
    String langDetected = detector.detect();
    System.out.println(langDetected);
Run Code Online (Sandbox Code Playgroud)

  • 我收到了Shuyo的回复,说明profiles.sm是短消息的语言配置文件,即twitter.我自信地认为'sm'意味着'短信'.希望这可以帮助. (2认同)

vic*_*irk 3

看起来该库只接受文件。您可以更改代码并尝试向上游提交更改。或者将您的资源写入临时文件并让它加载它。