Inverted index: Difference between revisions
Content added Content deleted
m (→{{header|C}}) |
(→{{header|D}}: added D) |
||
Line 964: | Line 964: | ||
(defparameter *result* (lookup *index* *query*)) |
(defparameter *result* (lookup *index* *query*)) |
||
(format t "Result for query ~s: ~{~a~^, ~}~%" *query* *result*)</lang> |
(format t "Result for query ~s: ~{~a~^, ~}~%" *query* *result*)</lang> |
||
=={{header|D}}== |
|||
<lang d>import std.stdio, std.algorithm, std.file, std.string; |
|||
void parseFile(in string fn, ref string[][string] idx) { |
|||
if (!exists(fn) || !isFile(fn)) |
|||
throw new Exception("File not found"); |
|||
foreach (word; readText(fn).splitter()) { |
|||
if (word in idx) { |
|||
if (canFind(idx[word], fn)) |
|||
continue; |
|||
} |
|||
idx[word] ~= fn; |
|||
} |
|||
} |
|||
void main() { |
|||
string[][string] index; |
|||
auto filenames = ["a.txt", "b.txt", "c.txt"]; |
|||
foreach (fname; filenames) |
|||
parseFile(fname, index); |
|||
while (true) { |
|||
writef("\nEnter a word to search for: (q to quit): "); |
|||
auto w = readln().strip(); |
|||
if (w.toLower() == "q") { |
|||
writeln("quitting"); |
|||
break; |
|||
} |
|||
if (w in index) |
|||
writefln("'%s' found in%( %)", w, index[w]); |
|||
else |
|||
writefln("'%s' not found", w); |
|||
} |
|||
}</lang> |
|||
<pre>Enter a word to search for: (q to quit): cat |
|||
'cat' not found |
|||
Enter a word to search for: (q to quit): dog |
|||
'dog' not found |
|||
Enter a word to search for: (q to quit): five |
|||
'five' found in "b.txt" |
|||
Enter a word to search for: (q to quit): one |
|||
'one' found in "a.txt" "c.txt" |
|||
Enter a word to search for: (q to quit): seven |
|||
'seven' found in "c.txt" |
|||
Enter a word to search for: (q to quit): q |
|||
quitting</pre> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |