5

テキストドキュメントとクエリがあります(クエリは複数の単語である可能性があります)。ドキュメント内で発生するすべてのクエリの位置を見つけたい。

documentText.indexOf(query)または正規表現を使用することを考えましたが、機能させることができませんでした。

私は次の方法で終わります:

まず、というdataTypeを作成しましたQueryOccurrence

public class QueryOccurrence implements Serializable{
  public QueryOccurrence(){}
  private int start;
  private int end;      

  public QueryOccurrence(int nameStart,int nameEnd,String nameText){
    start=nameStart;
    end=nameEnd;        
  }

  public int getStart(){
    return start;
  }

  public int getEnd(){
    return end;
  }

  public void SetStart(int i){
    start=i;
  }

  public void SetEnd(int i){
     end=i;
  }
}

次に、このデータ型を次のメソッドで使用しました。

    public static List<QueryOccurrence>FindQueryPositions(String documentText, String query){

    // Normalize do the following: lower case, trim, and remove punctuation
    String normalizedQuery = Normalize.Normalize(query);
    String normalizedDocument = Normalize.Normalize(documentText);

    String[] documentWords = normalizedDocument.split(" ");;               
    String[] queryArray = normalizedQuery.split(" ");


    List<QueryOccurrence> foundQueries = new ArrayList();
    QueryOccurrence foundQuery = new QueryOccurrence();

    int index = 0;

    for (String word : documentWords) {            

        if (word.equals(queryArray[0])){
            foundQuery.SetStart(index);
        }

        if (word.equals(queryArray[queryArray.length-1])){
            foundQuery.SetEnd(index);
            if((foundQuery.End()-foundQuery.Start())+1==queryArray.length){

                //add the found query to the list
                foundQueries.add(foundQuery);
                //flush the foundQuery variable to use it again
                foundQuery= new QueryOccurrence();
            }
        }

        index++;
    }
    return foundQueries;
}

このメソッドは、ドキュメント内で発生するすべてのクエリのリストと、それぞれの位置を返します。

このタスクを実行するためのより簡単で高速な方法を提案していただけますか。

ありがとう

4

1 に答える 1

11

最初のアプローチは良い考えでしたが、String.indexOfは正規表現をサポートしていません。

同様のアプローチを使用するもう1つの簡単な方法ですが、2段階の方法で、次のようになります。

List<Integer> positions = new ArrayList();
Pattern p = Pattern.compile(queryPattern);  // insert your pattern here
Matcher m = p.matcher(documentText);
while (m.find()) {
   positions.add(m.start());
}

ポジションは試合のすべての開始ポジションを保持します。

于 2012-11-10T23:05:52.313 に答える