Nội dung chƣơng trình

Một phần của tài liệu nghiên cứu thuật toán knuth-morris-pratt và ứng dụng (Trang 68 - 71)

Chƣơng trình sử dụng thƣ viện IFilter để đọc và phân tích các file của Microsoft Office và trích xuất văn bản từ các file đó. IFilter là một thƣ viện có sẵn trong window (từ window 2000 trở lên).

Hàm thực hiện đọc, phân tích và lập chỉ mục cho các file văn bản

public static string Parse(string filename) {

IFilter filter = null; try {

StringBuilder plainTextResult = new StringBuilder(); filter = loadIFilter(filename);

Số hóa bởi Trung tâm Học liệu http://www.lrc-tnu.edu.vn/ STAT_CHUNK ps = new STAT_CHUNK();

IFILTER_INIT mFlags = 0; uint i = 0;

filter.Init( mFlags, 0, null, ref i); int resultChunk = 0; resultChunk = filter.GetChunk(out ps); while (resultChunk == 0) { if (ps.flags == CHUNKSTATE.CHUNK_TEXT) { uint sizeBuffer = 60000; int resultText = 0;

while (resultText == Constants.FILTER_S_LAST_TEXT || resultText == 0) {

sizeBuffer = 60000;

System.Text.StringBuilder sbBuffer =

new System.Text.StringBuilder((int)sizeBuffer); resultText = filter.GetText(ref sizeBuffer, sbBuffer); if (sizeBuffer > 0 && sbBuffer.Length > 0)

{

string chunk = sbBuffer.ToString(0, (int)sizeBuffer); plainTextResult.Append(chunk); } } } resultChunk = filter.GetChunk(out ps); } return plainTextResult.ToString(); } finally { if (filter != null) Marshal.ReleaseComObject(filter);

Số hóa bởi Trung tâm Học liệu http://www.lrc-tnu.edu.vn/ }

- Hàm tạo bảng so sánh:

public static int[] BuildTable(string p) {

int[] result = new int[p.Length]; result[0] = 0;

for (int i = 1; i < p.Length - 1; i++) {

// The substring from p[1] to p[i] string s = p.Substring(0, i + 1);

var prefixes = Enumerable.Range(1, s.Length - 1) .Select(a => s.Substring(0, a)).ToList();

var suffixes = Enumerable.Range(1, s.Length - 1) .Select(a => s.Substring(a, s.Length - a)).ToList(); var common = prefixes.Intersect(suffixes).FirstOrDefault(); result[i] = (common == null) ? 0 : common.Length;

}

return result; }

}

- Hàm tìm kiếm

private static int SearchKMP(int[] x, string s) {

int n = s.Length; int l = x.Length; int find = 0;

Char[] charPattern = pattern.ToCharArray(); for (int i = 0; i < n; )

Số hóa bởi Trung tâm Học liệu http://www.lrc-tnu.edu.vn/ string a = s.Substring(i, l);

if (a.CompareTo(pattern).Equals(0)) {

return i; // Found match, return match position of the first letter }

// move position by BuildTable

Char[] charSubstring = a.ToCharArray(); int count = 0;

for (int j = 0; j < l; j++) {

if (charPattern[j] == charSubstring[j]) {

count++;// count of matched chars continue;

} else {

i += count - x[j]; // move forward steps = matched count - table value break;

} } }

return -999; // not found }

Một phần của tài liệu nghiên cứu thuật toán knuth-morris-pratt và ứng dụng (Trang 68 - 71)