5

我有一个文本文档和一个查询(查询可能不止一个词)。我想找到文档中所有出现的查询的位置。

我想到了documentText.indexOf(query)or 使用正则表达式,但我无法让它工作。

我最终得到以下方法:

首先,我创建了一个名为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 不支持正则表达式。

另一种使用类似方法但采用两步法的更简单方法如下:

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 回答