我正在使用 Apache Open NLP 的 NER。我已经成功地训练了我的自定义数据。在使用 name finder 时,我根据空格拆分给定的字符串并传递如下所示的字符串数组。
NameFinderME nameFinder = new NameFinderME(model);
String []sentence = input.split(" "); //eg:- input = Give me list of test case in project X
Span nameSpans[] = nameFinder.find(sentence);
在这里,当我使用 split 时,test 和 case 被作为单独的值给出,并且永远不会被名称查找器检测到。我怎么可能克服上述问题。有没有一种方法可以传递完整的字符串(不将其拆分为数组),这样测试用例将被视为一个整体?
最佳答案
您可以使用正则表达式来完成。尝试用这个替换第二行:
String []sentence = input.split("\\s(?<!(\\stest\\s(?=case\\s)))");
也许有更好的方法来编写表达式,但这对我有用,输出是:
Give
me
list
of
test case
in
project
X
编辑:如果您对详细信息感兴趣,请在此处查看我拆分的位置:https://regex101.com/r/6HLBnL/1
编辑 2: 如果您有很多单词没有分开,我写了一个方法来为您生成正则表达式。这是本例中的正则表达式的样子(如果您不想将“测试用例” 和“项目中” 分开):
\s(?<!(\stest\s(?=case\s))|(\sin\s(?=project\s)))
下面是一个简单的程序来演示它。在此示例中,您只需将不需要分隔的单词放入数组 unseparated
中.
class NoSeparation {
private static String[][] unseparated = {{"test", "case"}, {"in", "project"}};
private static String getRegex() {
String regex = "\\s(?<!";
for (int i = 0; i < unseparated.length; i++)
regex += "(\\s" + separated[i][0] + "\\s(?=" + separated[i][1] + "\\s))|";
// Remove the last |
regex = regex.substring(0, regex.length() - 1);
return (regex + ")");
}
public static void main(String[] args) {
String input = "Give me list of test case in project X";
String []sentence = input.split(getRegex());
for (String i: sentence)
System.out.println(i);
}
}
编辑 3: 以下是处理超过 2 个单词的字符串的非常肮脏的方法。它有效,但我很确定您可以以更有效的方式进行操作。它在短输入中工作正常,但在较长的输入中可能会很慢。
你必须把不应该拆分的单词放在一个二维数组中,如unseparated
.如果您不想使用 %%
,您还应该选择一个分隔符出于某种原因(例如,如果您的输入有可能包含它)。
class NoSeparation {
private static final String SEPARATOR = "%%";
private static String[][] unseparated = {{"of", "test", "case"}, {"in", "project"}};
private static String[] splitString(String in) {
String[] splitted;
for (int i = 0; i < unseparated.length; i++) {
String toReplace = "";
String replaceWith = "";
for (int j = 0; j < unseparated[i].length; j++) {
toReplace += unseparated[i][j] + ((j < unseparated[i].length - 1)? " " : "");
replaceWith += unseparated[i][j] + ((j < unseparated[i].length - 1)? SEPARATOR : "");
}
in = in.replaceAll(toReplace, replaceWith);
}
splitted = in.split(" ");
for (int i = 0; i < splitted.length; i++)
splitted[i] = splitted[i].replaceAll(SEPARATOR, " ");
return splitted;
}
public static void main(String[] args) {
String input = "Give me list of test case in project X";
// Uncomment this if there is a chance to have multiple spaces/tabs
// input = input.replaceAll("[\\s\\t]+", " ");
for (String str: splitString(input))
System.out.println(str);
}
}
关于java - 使用 Apache OpenNLP 查找以空格分隔的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41935909/