我有一个文本,并将其分成以空格分隔的单词。
我正在对单位进行分类,如果它出现在同一个单词中,它们就会起作用。例如"100m","90kg","140°F","US$500"),但如果它们单独出现,每个部分都在一个单词中,我就会遇到问题。: '100°C', 'US$ 450', '150 km')。
分类器算法可以理解单元在右侧,缺失值在左侧还是右侧。
我的问题是如何遍历列表中的所有单词,为分类器提供正确的单词。
这只是一个代码示例。我已经试过很多方法了。
for(String word: words){
String category = classifier.classify(word);
if(classifier.needPreviousWord()){
// ?
}
if(classifier.needNextWord()){
// ?
}
}
换句话说,我需要遍历列表,对所有单词进行分类,如果需要测试前一个单词,则提供最后一个单词和单元。如果需要下一个单词,提供单位和下一个单词。看起来很简单,但是我不知道该怎么做。
不要在for循环中使用隐式迭代器,而要使用显式迭代器。然后你可以随意来回切换。
Iterator<String> i = words.iterator();
while (i.hasNext()) {
String category = classifier.classify(i.next());
if(classifier.needPreviousWord()){
i.previous();
}
if(classifier.needNextWord()){
i.next();
}
}
这是不完整的,因为我不知道你的分类器到底是做什么的,但它应该给你一个如何继续的想法。
这可能有帮助。
public static void main(String [] args)
{
List<String> words = new ArrayList<String>();
String previousWord = "";
String nextWord = "";
for(int i=0; i < words.size(); i++) {
if(i > 0) {
previousWord = words.get(i-1);
}
String currentWord = words.get(i);
if(i < words.size() - 1) {
nextWord = words.get(i+1);
} else {
nextWord = "";
}
String category = classifier.classify(word);
if(category.needPreviousWord()){
if(previousWord.length() == 0) {
System.out.println("ERROR: missing previous unit");
} else {
System.out.println(previousWord + currentWord);
}
}
if(category.needNextWord()){
if(nextWord.length() == 0) {
System.out.println("ERROR: missing next unit");
} else {
System.out.println(currentWord + nextWord);
}
}
}
}