Bei automatisierten Textauswertungen, wie z.B. Suchanfragen, benötigt man oft eine Stopwortliste. Dort werden Wörter welche wenig nützlich sind aufgelistet und bei der automatischen Verarbeitung ausgelassen.
Das folgende Snippet stellt einen einfachen Assistenten zur Erzeugung einer solchen Liste bereit. Als Ausgangspunkt dient dabei ein beliebiger Textabschnitt.
<?php
/**
* Eine Stopwortliste erstellen
*/
setlocale(LC_ALL, 'de_DE@euro');
// alphabetisch geordnete Wortliste aus Text zurückgeben
function getwords($text)
{
$stack = array();
$success = preg_match_all ('#\b([a-z]+)\b#iU', $text, $matches);
$tmp = $matches[1];
$tmp = array_map('trim', $tmp);
$tmp = array_filter($tmp);
$tmp = array_unique($tmp);
natcasesort($tmp);
return $tmp;
}
function wordlist($text, $current)
{
$tmp = array_diff(getwords($text), getwords($current));
if (isset($_POST['new']) && is_array($_POST['new'])){
$tmp = array_diff($tmp, $_POST['new']);
}
$n = 0;
$stack = array();
if (count($tmp) > 0){
while ($word = array_shift($tmp)){
$stack[] = sprintf('<input name="new[]" type="checkbox" value="%1$s"id="lbl%2$s">
<label for="lbl%2$s">%1$s</label><br>', htmlentities($word), $n);
$n++;
}
}
$s = join ("\n", $stack);
return $s;
}
function stopwordlist($text)
{
$current = getwords($text);
$add = isset($_POST['new']) ? $_POST['new'] : array();
$new = array_merge($current, $add);
natcasesort($new);
$s = join ("\n", array_unique($new));
return $s;
}
$stopwords = '';
$list = '';
$source = '';
if (isset($_POST['source']) && !empty($_POST['source'])){
$_POST['source'] = get_magic_quotes_gpc()
? stripslashes($_POST['source'])
: $_POST['source'];
$_POST['stopwords'] = get_magic_quotes_gpc()
? stripslashes($_POST['stopwords'])
: $_POST['stopwords'];
$list = wordlist($_POST['source'], $_POST['stopwords']);
$source = $_POST['source'];
$stopwords = stopwordlist($_POST['stopwords']);
$msg = htmlentities($_POST['source']);
}else{
$source = <<< EOT
Das ist ein Beispiel
--------------------
Eine Stopwortliste enthält Begriffe welche bei einer Suchanfrage ignoriert werden
sollen.
Das sind in der Regel also Wörter welche sehr häufig vorkommen oder keine relevante
Bedeutung haben.
EOT;
}
echo <<< EOT
<form method="post" action="{$_SERVER['PHP_SELF']}">
<label>Ausgangstext</label>
<br/>
<textarea name="source" rows="10" cols="70">$source</textarea>
<br/>
<br />
<label>Stopwörter</label>
<br/>
<textarea name="stopwords" rows="10" cols="70">$stopwords</textarea>
<br/>
<input type="submit" value="Stopwortliste erstellen/aktualisieren">
<br/>
<h2>Erkannte Worte</h2>
$list
</form>
EOT;
?>