今天我找到了这个Java实现的Frank Liang的英语或德语断字算法模式的
texhyphj,它工作得非常好,并且可以在Maven Central中使用。
注意:重要的是要删除
.tex
模式文件的最后几行,否则这些文件就不能被当前版本的Maven Central加载。
要加载和使用
断词器(hyphenator)
,您可以使用以下Java代码片段。
texTable
是包含所需模式的
.tex
文件的名称。 这些文件可在项目Github网站上获取。
private Hyphenator createHyphenator(String texTable) {
Hyphenator hyphenator = new Hyphenator();
hyphenator.setErrorHandler(new ErrorHandler() {
public void debug(String guard, String s) {
logger.debug("{},{}", guard, s);
}
public void info(String s) {
logger.info(s);
}
public void warning(String s) {
logger.warn("WARNING: " + s);
}
public void error(String s) {
logger.error("ERROR: " + s);
}
public void exception(String s, Exception e) {
logger.error("EXCEPTION: " + s, e);
}
public boolean isDebugged(String guard) {
return false;
}
});
BufferedReader table = null;
try {
table = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader()
.getResourceAsStream((texTable)), Charset.forName("UTF-8")));
hyphenator.loadTable(table);
} catch (Utf8TexParser.TexParserException e) {
logger.error("error loading hyphenation table: {}", e.getLocalizedMessage(), e);
throw new RuntimeException("Failed to load hyphenation table", e);
} finally {
if (table != null) {
try {
table.close();
} catch (IOException e) {
logger.error("Closing hyphenation table failed", e);
}
}
}
return hyphenator;
}
接下来,连字器
已经可以使用。为了检测音节,基本思想是在提供的连字符处将术语分割。
String hyphenedTerm = hyphenator.hyphenate(term);
String hyphens[] = hyphenedTerm.split("\u00AD");
int syllables = hyphens.length;
由于API没有返回正常的"-"
,所以您需要在"\u00AD
"上进行拆分。
这种方法比Joe Basirico的答案表现更好,因为它支持许多不同的语言,并且可以更准确地检测德语连字号。