Inverted index: Difference between revisions

Shorter D entry, used text files from Wikipedia
(→‎{{header|D}}: regex splitter)
(Shorter D entry, used text files from Wikipedia)
Line 966:
 
=={{header|D}}==
<lang d>import std.stdio, std.algorithm, std.filestring, std.stringfile, std.regex;
 
void parseFile(in string fn, ref string[][string] idx) {
Line 972:
throw new Exception("File not found");
 
foreach (immutable word; readText(fn).splitter(regex(r"\W"))) {
if (!idx.get(word, in idxnull).canFind(fn)) {
if (canFind(idx[word], ~= fn));
continue;
}
idx[word] ~= fn;
}
}
 
Line 984 ⟶ 980:
string[][string] index;
 
foreach (immutable fileName; ["inverted_index0.txt",
auto filenames = ["a.txt", "b.txt", "c.txt"];
"inverted_index1.txt",
foreach (fname; filenames)
"inverted_index2.txt"])
parseFile(fnamefileName, index);
 
while (true) {
writef("\nEnter a word to search for: (q to quit): ");
autoimmutable 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>
Both the demo text files and the queries are from the Wikipedia page, they contain:
<pre>Enter a word to search for: (q to quit): cat
it is what it is
'cat' not found
 
what is it
 
it is a banana
{{out}}
<pre>Enter a word to search for: (q to quit): cata
'a' found in "inverted_index2.txt".
 
Enter a word to search for: (q to quit): dogbanana
'banana' found in "inverted_index2.txt".
'dog' not found
 
Enter a word to search for: (q to quit): fiveis
'fiveis' found in "binverted_index0.txt" "inverted_index1.txt" "inverted_index2.txt".
 
Enter a word to search for: (q to quit): oneit
'oneit' found in "ainverted_index0.txt" "cinverted_index1.txt" "inverted_index2.txt".
 
Enter a word to search for: (q to quit): sevenwhat
'sevenwhat' found in "cinverted_index0.txt" "inverted_index1.txt".
 
Enter a word to search for: (q to quit): q
quitting.</pre>
 
=={{header|Factor}}==