我正在做一个项目,我想能够解析一些文本并找到名词,我想解析的很多文本中都有代词,例如=>“鹦鹉艾玛是一只鸟。她住在一棵大树上。”。
我不想使用“She’s”等。因为它们在我正在使用的词典中不被视为名词,所以我一直在研究一种方法,用以前出现的名称替换She等。因此,上述示例将输出到=>“鹦鹉艾玛是一只鸟。艾玛住在一棵大树上。”。
当我有一个小样本时,这种方法很有效,但是当我在一篇文本中与3-4个不同的人合作时,它不起作用。
public static String replacePronouns(String text, ArrayList<String> dictionary) {
String[] strArray = text.replaceAll("\\.", " .").replaceAll("\\,", "").split("\\s+");
String previousName = "";
for(int i = 0; i < strArray.length; i++ ) {
//we'll have to set this to be more dynamic -> change to pronouns in dicitonary
if(strArray[i].equals("His") || strArray[i].equals("She") || strArray[i].equals("she") || strArray[i].equals("him") || strArray[i].equals("he") || strArray[i].equals("her")) {
for(int j = (i-1); j>=0; j--) {
int count = dictionary.size()-1;
boolean flag = false;
while(count>=0 && flag==false) {
if(strArray[j].equals(dictionary.get(count).split(": ")[1]) && dictionary.get(count).split(": ")[0].equals("Name")) {
previousName = strArray[j];
flag = true; }
count--;
} }
strArray[i] = previousName; } }
return Arrays.toString(strArray).replaceAll("\\[", "").replaceAll("\\,", "").replaceAll("\\]", "");
}
它接收我的文本
String text = "Karla was a bird and she had beautifully colorful feathers. She lived in a tall tree.
ArrayList<String> dictionary = new ArrayList<>();
dictionary.add("Name: hunter");
dictionary.add("Name: Karla");
dictionary.add("Noun: hawk");
dictionary.add("Noun: feathers");
dictionary.add("Noun: tree");
dictionary.add("Noun: arrows");
dictionary.add("Verb: was a");
dictionary.add("Verb: had");
dictionary.add("Verb: missed");
dictionary.add("Verb: knew");
dictionary.add("Verb: offered");
dictionary.add("Verb: pledged");
dictionary.add("Verb: shoot");
但在这个例子中,它总是输出卡拉,即使我们让“猎人开枪”在同一条线上。
如果您能提供任何帮助,解释为什么这不起作用,我们将不胜感激