Preg-Match-All - Synonym File


Preg-Match-All - Synonym File

我正在编写一个php脚本,它将解析一个文件(synonys .dat),并将同义词列表与其父词协调起来,大约有150k个单词。

示例from file:

1|2
(adj)|one|i|ane|cardinal 
(noun)|one|I|ace|single|unity|digit|figure
1-dodecanol|1
(noun)|lauryl alcohol|alcohol
1-hitter|1
(noun)|one-hitter|baseball|baseball game|ball
10|2
(adj)|ten|x|cardinal 
(noun)|ten|X|tenner|decade|large integer
100|2
(adj)|hundred|a hundred|one hundred|c|cardinal 
(noun)|hundred|C|century|one C|centred|large integer
1000|2
(adj)|thousand|a thousand|one thousand|m|k|cardinal 
(noun)|thousand|one thousand|M|K|chiliad|G|grand|thou|yard|large integer
**10000|1
(noun)|ten thousand|myriad|large**

在上面的例子中,我想链接10000,myriad, large到单词1000。

我已经尝试了使用file_get_contents将.dat文件读取到内存中的各种方法,然后在'n处爆炸文件,并使用各种数组搜索技术来查找"父"字及其同义词。然而,这是非常缓慢的,而且经常崩溃我的web服务器。

我相信我需要做的是使用preg_match_all来爆炸字符串,然后只是迭代字符串,在适当的地方插入到我的数据库。

$contents = file_get_contents($page);
preg_match_all("/([^'s]+)'|[0-9].*/",$contents,$out, PREG_SET_ORDER);

匹配每个

1|2
1-dodecanol|1
1-hitter|1

但是我不知道如何在每个匹配项之间链接字段,即同义词本身。

此脚本旨在运行一次,以获得所有信息到我的数据库适当。对于那些感兴趣的人,我有一个数据库'synonym_index',其中包含每个单词以及单词的唯一id。然后是另一个表'synonym_listing',其中包含'word_id'列和' synonym_id '列,其中每列是synonym_index的外键。每个word_id可以有多个synonym_id

非常感谢你的帮助!

您可以使用explosion()将每行拆分为字段。(或者,根据输入的精确格式,fgetcsv()可能是更好的选择。)

说明性示例,几乎肯定需要根据您的特定用例和数据格式进行调整:

$infile = fopen('synonyms.dat', 'r');
while (!feof($infile)) {
    $line = rtrim(fgets($infile), "'r'n");
    if ( $line === '' ) {
        continue;
    }
    // Line follows the format HEAD_WORD|NUMBER_OF_SYNONYM_LINES
    list($headWord, $n) = explode('|', $line);
    $synonyms = array();
    // For each synonym line...
    while ( $n-- ) {
        $line = rtrim(fgets($infile), "'r'n");
        $fields = explode('|', $line);
        $partOfSpeech = substr(array_shift($fields), 1, -1);
        $synonyms[$partOfSpeech] = $fields;
    }
    // Now here, when $headWord is '**10000', $synonyms should be array(
    //     'noun' => array('ten thousand', 'myriad', 'large**')
    // )
}

哇,对于这种类型的功能,您有带有表和索引的数据库。PHP是为请求/响应提供服务的,而不是将大文件读入内存。我建议你把数据存入数据库。那将会快得多——而且它就是为之而生的。