在中文文本语料库中搜索只包含某些字符的句子

时间:2012-04-20 12:51:04

标签: php parsing search pattern-matching cjk

目标:搜索成千上万个中文句子的数组,以便找到专门包含“已知字符”数组中字符的句子。

例如: 假设我的语料库由以下句子组成:1)我去中国.2)妳爱他.3)你在哪里? 我只是“知道”或想要专门包含这些字符的句子:1)我2)中3)国4)你5)在6)去7)爱8)哪9)里。 第一个句子将作为结果返回,因为它的所有三个字符都在我的第二个数组中。第二句话会被拒绝,因为我没有要求妳或他。结果将返回第三句。忽略标点符号(以及任何字母数字字符)。

我有一个工作脚本(下图)。我想知道这是否是一种有效的方式。如果您有兴趣,请查看并建议更改,自己编写或提供一些建议。我从this script收集了一些并检查了一些stackoverflow问题,但他们没有解决这个问题。

<?php
$known_characters = parse_file("FILENAME") // retrieves target characters
$sentences = parse_csv("FILENAME"); // retrieves the text corpus

$number_wanted = 30; // number of sentences to attempt to retrieve

$found = array(); // stores results
$number_found = 0; // number of results
$character_known = false; // assume character is not known
$sentence_known = true; // assume sentence matches target characters

foreach ($sentences as $s) {

    // retrieves an array of the sentence
    $sentence_characters = mb_str_split($s->ttext);

    foreach ($sentence_characters as $sc) {
        // check to see if the character is alpha-numeric or punctuation
        // if so, then ignore.
        $pattern = '/[a-zA-Z0-9\s\x{3000}-\x{303F}\x{FF00}-\x{FF5A}]/u';
        if (!preg_match($pattern, $sc)) {
            foreach ($known_characters as $kc) {;
                if ($sc==$kc) {
                    // if character is known, move to next character
                    $character_known = true;
                    break;
                }
            }
        } else {
            // character is known if it is alpha-numeric or punctuation
            $character_known = true;
        }
        if (!$character_known) {
            // if character is unknown, move to next sentence
            $sentence_known = false;
            break;
        }
        $character_known = false; // reset for next iteration
    }
    if ($sentence_known) {
        // if sentence is known, add it to results array
        $found[] = $s->ttext;
        $number_found = $number_found+1;
    }
    if ($number_found==$number_wanted)
        break; // if required number of results are found, break

    $sentence_known = true; // reset for next iteration 
}
?>

1 个答案:

答案 0 :(得分:0)

在我看来应该这样做:

$pattern = '/[^a-zA-Z0-9\s\x{3000}-\x{303F}\x{FF00}-\x{FF5A}我中国你在去爱哪里]/u';
if (preg_match($pattern, $sentence) {
    // the sentence contains characters besides a-zA-Z0-9, punctuation
    // and the selected characters
} else {
    // the sentence contains only the allowed characters
}

确保将源代码文件保存为UTF-8。