Skip to content

Commit

Permalink
Search for keyword in the given context
Browse files Browse the repository at this point in the history
  • Loading branch information
rpereira committed Jun 24, 2016
1 parent 3a9426f commit 824827d
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
6 changes: 6 additions & 0 deletions build.xml
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,10 @@
<classpath refid="classpath.examples"/>
</java>
</target>

<target name="run-kwik-example" depends="examples-compile">
<java classname="KWIK">
<classpath refid="classpath.examples"/>
</java>
</target>
</project>
68 changes: 68 additions & 0 deletions examples/KWIK.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* Keyword-in-context search.
*
* Computes all of the occurrences of a keyword in a string, with surrounding
* context.
*/
public class KWIK {

/**
* Reads the contents of the specified file and returns them as a string.
*
* @param filePath the path to the input file
*/
private static String readFileAsString(String filePath) {
File f = new File(filePath);
BufferedReader reader = null;
StringBuilder text = new StringBuilder();
String line = null;

try {
reader = new BufferedReader(new FileReader(f));
while ((line = reader.readLine()) != null) {
text.append(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}

return text.toString();
}

public static void main(String[] args) {
String text = readFileAsString("./data/brave_new_world.txt");
// int context = Integer.parseInt(args[0]);
// String query = args[1];

// number of characters of surrounding context in each side
int context = 20;

// query string
String query = "world";

int length = text.length();

// build suffix array
SuffixArray sa = new SuffixArray(text);

for (int i = sa.rank(query); i < length && sa.selectAsString(i).startsWith(query); i++) {
int from = Math.max(0, sa.indexOf(i) - context);
int to = Math.min(length-1, from + query.length() + 2*context);
System.out.println(text.substring(from, to));
}
}
}
1 change: 1 addition & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,6 @@ Here's the complete list of available examples.
* `ant run-suffixArray-example`
* `ant run-lrs-example`
* `ant run-lcs-example`
* `ant run-kwik-example`

*Note: a better approach for running the examples is yet to be determined.*

0 comments on commit 824827d

Please sign in to comment.