使用Apache OpenNLP在句子中查找位置时如何解决问题

时间:2018-11-14 16:50:43

标签: java apache android-studio-3.0 opennlp

package com.example.dell.apacheopennlp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import opennlp.tools.namefind.NameFinderME;
import opennlp.tools.namefind.TokenNameFinderModel;
import opennlp.tools.tokenize.TokenizerME;
import opennlp.tools.tokenize.TokenizerModel;
import opennlp.tools.util.Span;
public class apacheOpenNLP extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_apache_open_nlp);
        final TextView txt = (TextView) findViewById (R.id.txtView);

        InputStream inputStream = null;
        TokenizerModel tokenModel =null;
        try{
            inputStream = getAssets().open("en-token.bin");
            tokenModel = new TokenizerModel (inputStream);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            txt.setText (e.toString ()+" inside catch of token");
        }

        if(tokenModel!=null) {
            TokenizerME tokenizer = new TokenizerME (tokenModel);
            String paragraph = "Tutorialspoint is located in Hyderabad";
            String tokens[] = tokenizer.tokenize (paragraph);
            InputStream locationInputStream=null;
            TokenNameFinderModel locationModel = null;

            try {

                locationInputStream = getAssets ( ).open ("en-ner-location.bin");
                locationModel = new TokenNameFinderModel (locationInputStream);

            } catch (IOException e) {
                e.printStackTrace ( );
                txt.setText (e.toString ()+" inside catch of location");
            }

            if (locationModel != null) {
                NameFinderME nameFinder = new NameFinderME (locationModel);
                Span nameSpans[] = nameFinder.find (tokens);

                String result = null;
                for (Span s : nameSpans)
                    //result=  s.toString()+"  "+tokens[s.getStart()];
                    result += s.toString ( );
                txt.setText (result);
            }
            else{
               // txt.setText ("Location model is empty");
            }
        }
    }
}

我正在使用Apache OpenNLP提取句子中的位置。我调试了代码,发现在NameFinderME nameFinder = new NameFinderME(locationModel)之后; android应用程序崩溃,显示一条消息“该应用程序已停止工作” 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可以尝试将nameFinder更改为声明为TokenNameFinder接口类型吗?

只需尝试更换

NameFinderME nameFinder = null

使用

TokenNameFinder nameFinder = null

所有其他都应该相同。