【发布时间】:2018-03-29 13:01:15
【问题描述】:
我正在做一个项目,我希望能够解析一些文本并找到名词,而我想要解析的很多文本中都有代词,例如 =>“Emma the parrot is a鸟。她住在一棵高大的树上”。
我不想使用“She's”等,因为它们在我正在使用的字典中不被视为名词,因此我一直在研究一种方法,将 She 等替换为之前出现的一个名字。所以上面的例子会输出为 => "Emma the parrot is a bird. Emma living in a high tree".
当我有一个小样本时,该方法运行良好,但是当我在一个文本中与 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");
但在这个例子中它总是输出 Karla,即使我们在同一个字符串中有“The hunter shot his gun”。 任何有关为什么这不起作用的帮助将不胜感激
【问题讨论】:
-
如果我理解正确,这可能具有挑战性,例如
Emma talked to Karla, She told her ...,这可能意味着两件事,Emma talked to Karla, Emma told her ...或Emma talked to Karla, Karla told her ...。是哪个? -
@BaSsGaz 这是一个我还没有研究过的问题(但是这将是一个问题)。现在更重要的是让实际的代词方法按预期工作。在你的例子中,当我确实遇到这个问题时,我会用“艾玛和卡拉谈过,艾玛告诉卡拉”来处理类似的问题
标签: java text-processing